diff --git a/VERSION.md b/VERSION.md index 7b5bc55..97b7714 100644 --- a/VERSION.md +++ b/VERSION.md @@ -2,31 +2,40 @@ ## [Version 1.0.0] - 2024-04-11 -### History +- History -0. 较于曾今版本重新开发,由于安全问题重新启用git。 -1. 修改了静态网页的代码,并使用booststrap框架和anchor模板。 -2. 对于曾经的express框架,对代码进行重构。 -3. 使用了dotenv模块,加载配置项。 -4. 修改部分文件架构尤其是各类隐藏文件夹。 +1. 较于曾今版本重新开发,由于安全问题重新启用git。 +2. 修改了静态网页的代码,并使用booststrap框架和anchor模板。 +3. 对于曾经的express框架,对代码进行重构。 +4. 使用了dotenv模块,加载配置项。 +5. 修改部分文件架构尤其是各类隐藏文件夹。 ## [Version 1.0.1-alpha] - 2024-04-13 -### New Features +- New Features -0. 大量修改文件结构,详情见README.md。 -1. 添加了登录,注册,管理员的功能。 -2. 使用better-sqlite3重构数据库接口。 -3. 重构代码结构使其路由更清晰,更易于使用cookie(未来将会重构cookie代码)。 -4. 添加VERSION.md文件,记录版本历史。 -5. 添加各种细节。 +1. 大量修改文件结构,详情见README.md。 +2. 添加了登录,注册,管理员的功能。 +3. 使用better-sqlite3重构数据库接口。 +4. 重构代码结构使其路由更清晰,更易于使用cookie(未来将会重构cookie代码)。 +5. 添加VERSION.md文件,记录版本历史。 +6. 添加各种细节。 -### Bugs Fixed +- Bugs Fixed 1. 修改default.env文件,使其初始化密码简易包括硬性写入代码中的密码(default.env文件就是代码内的各项参数的默认值)。 ## [Version 1.1.0-alpha] - 2024-06-02 ~ 2024-07-23 -### New Features +- New Features 1. 重构代码,使用Vue3重构前端。 +2. 禁用登录功能。 +3. 根据API修改文件读取。 + +## [Version 1.1.0-beta] - 2024-08 + +- New Features + +1. 使用typescript重构代码。 +2. 修改VERSION.md文件。 diff --git a/controllers/files/api.js b/controllers/files/api.js deleted file mode 100644 index 392b229..0000000 --- a/controllers/files/api.js +++ /dev/null @@ -1,11 +0,0 @@ -const router = require('express').Router(); - -const getFilePath = require('./index'); -// router.get('/json/:filename', getJsonFile); -router.get('/:type/*', (req, res) => { - // console.log(req.params); - const path = getFilePath(`${req.params.type}/${req.params[0]}.${req.query.type}`); - res.sendFile(path); -}) - -module.exports = router; \ No newline at end of file diff --git a/controllers/files/json.js b/controllers/files/json.js deleted file mode 100644 index 4a3e97c..0000000 --- a/controllers/files/json.js +++ /dev/null @@ -1,8 +0,0 @@ -const { getJsonPath } = require('../../services/files'); - -function getJsonFile(req, res, next) { - const filename = req.params.filename; - res.sendFile(getJsonPath(filename)); -}; - -module.exports = { getJsonFile }; \ No newline at end of file diff --git a/package.json b/package.json index 047d196..a76e14b 100644 --- a/package.json +++ b/package.json @@ -2,10 +2,11 @@ "name": "web_zzyxyz", "version": "1.0.1", "description": "None", - "main": "./main/web.js", "scripts": { - "test": "nodemon ./main/web.js", - "start": "node ./main/web.js" + "build": "tsc && node ./dist/src/main.js", + "start": "ts-node ./src/main", + "dev": "nodemon --watch ./src/**/*.* --ext ts,js,json --exec \"ts-node ./src/main\"", + "err": "echo \"Error: no test specified\" && exit 1" }, "author": "zzy", "license": "ISC", @@ -15,7 +16,13 @@ "dotenv": "^16.4.5", "express": "^4.19.2", "jsonwebtoken": "^9.0.2", - "nodemon": "^3.1.0", "ws": "^8.17.0" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/node": "^22.5.0", + "nodemon": "^3.1.4", + "ts-node": "^10.9.2", + "typescript": "^5.5.4" } } diff --git a/routes/api.js b/routes/api.js deleted file mode 100644 index 0634c4f..0000000 --- a/routes/api.js +++ /dev/null @@ -1,8 +0,0 @@ -const express = require('express'); - -const router = express.Router(); - -router.use('/files', require('../controllers/files/api.js')); -// router.use('/home') - -module.exports = router; \ No newline at end of file diff --git a/server.js b/server.ts similarity index 61% rename from server.js rename to server.ts index 77e7a7f..1d6a212 100644 --- a/server.js +++ b/server.ts @@ -1,19 +1,22 @@ -const express = require('express'); -const path = require('path'); -require('dotenv').config(); -env = process.env; +import express, { Application, Request, Response, NextFunction } from 'express'; +import path from 'path'; +import dotenv from 'dotenv'; +dotenv.config(); +process.env.ROOT_DIR = path.resolve(__dirname); +const env = process.env; -const app = express(); +export const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(require('cookie-parser')()); -dist = path.join(__dirname, env.STATIC_PATH ?? 'static') +const dist = path.join(__dirname, env.STATIC_PATH ?? 'static'); // 静态资源服务,假设你的dist目录包含了编译后的Vue应用 app.use(express.static(dist)); -app.use('/api', require('./routes/api.js')); +import router from './src/routes/api'; +app.use('/api', router); // // catch 404 and forward to error handler // app.use(function(req, res, next) { @@ -22,12 +25,12 @@ app.use('/api', require('./routes/api.js')); // }); // 所有未匹配到的请求都重定向到index.html,使用vue3的SPA匹配 -app.get('*', (req, res) => { +app.get('*', (req: Request, res: Response) => { res.sendFile(path.join(dist, '/index.html')); }); // error handler -app.use(function(err, req, res, next) { +app.use(function(err: any, req: Request, res: Response, next: NextFunction) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = env.MOD === 'development' ? err : {}; @@ -36,6 +39,4 @@ app.use(function(err, req, res, next) { // render the error page res.status(err.status || 500); res.end('

error

'); -}); - -module.exports = app; \ No newline at end of file +}); \ No newline at end of file diff --git a/services/files.js b/services/files.js deleted file mode 100644 index f140190..0000000 --- a/services/files.js +++ /dev/null @@ -1,15 +0,0 @@ -const utils = require('../utils.js'); -const path = require('path'); -const fs = require('fs'); - -const DATA_JSON_PATH = path.resolve(utils.DATA_PATH, 'json'); - -if (!fs.existsSync(DATA_JSON_PATH)) { - fs.mkdirSync(DATA_JSON_PATH, { recursive: true }); -} - -function getJsonPath(filename) { - return path.resolve(DATA_JSON_PATH, filename); -} - -module.exports = { getJsonPath }; \ No newline at end of file diff --git a/src/controllers/files/api.ts b/src/controllers/files/api.ts new file mode 100644 index 0000000..73f85cb --- /dev/null +++ b/src/controllers/files/api.ts @@ -0,0 +1,15 @@ +import { Router } from 'express'; +import { Request, Response } from 'express'; +const router = Router(); + +import { getFilePath } from './index'; +// router.get('/json/:filename', getJsonFile); +router.get('/:type/*', (req: Request, res: Response) => { + if (process.env.MOD === 'dev') { + console.log(req.params); + } + const path = getFilePath(`${req.params.type}/${req.params[0]}.${req.query.type}`); + res.sendFile(path); +}) + +export default router; \ No newline at end of file diff --git a/controllers/files/files.js b/src/controllers/files/files.js similarity index 100% rename from controllers/files/files.js rename to src/controllers/files/files.js diff --git a/controllers/files/index.js b/src/controllers/files/index.ts similarity index 55% rename from controllers/files/index.js rename to src/controllers/files/index.ts index 47f8081..76a9113 100644 --- a/controllers/files/index.js +++ b/src/controllers/files/index.ts @@ -1,11 +1,9 @@ -const {join} = require('path'); -const fs = require('fs'); -require('dotenv').config(); -const env = process.env; -const root = join(__dirname, '../../'); +import { join } from 'path'; +import fs from 'fs'; +const root = join(__dirname, '../../../'); -function getFilePath(path) { - return join(root, `${env.FILE_PATH}`, path); +export function getFilePath(path: string) { + return join(`${process.env.ROOT_DIR}`, `${process.env.FILE_PATH}`, path); } // function getFile(path, callback) { @@ -19,6 +17,4 @@ function getFilePath(path) { // callback(data); // }); -// } - -module.exports = getFilePath; \ No newline at end of file +// } \ No newline at end of file diff --git a/controllers/users/users.js b/src/controllers/users/_users.js similarity index 100% rename from controllers/users/users.js rename to src/controllers/users/_users.js diff --git a/controllers/users/api.js b/src/controllers/users/api.js similarity index 100% rename from controllers/users/api.js rename to src/controllers/users/api.js diff --git a/services/users.js b/src/controllers/users/users.js similarity index 97% rename from services/users.js rename to src/controllers/users/users.js index e8a13eb..1ad3335 100644 --- a/services/users.js +++ b/src/controllers/users/users.js @@ -1,7 +1,7 @@ const utils = require('../utils.js'); const path = require('path'); -const auth = require('../utils/auth_utils'); -const db = require('../utils/db'); +const auth = require('../../utils/auth_utils.js'); +const db = require('../../utils/db.js'); db.createTable('users', [ {name :'id', type: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'}, diff --git a/main/web.js b/src/main.ts similarity index 81% rename from main/web.js rename to src/main.ts index 9ba6190..18b74a0 100644 --- a/main/web.js +++ b/src/main.ts @@ -2,10 +2,11 @@ * Module dependencies. */ -const app = require('../server.js'); -const http = require('http'); -require('dotenv').config(); -env = process.env; +import { app } from '../server'; +import { createServer } from 'http'; +import dotenv from 'dotenv'; +dotenv.config(); +const env = process.env; /** * Get port from config and store in Express. @@ -16,7 +17,7 @@ app.set('port', port); /** * Create HTTP server. */ -const server = http.createServer(app); +const server = createServer(app); /** * Listen on provided port, on all network interfaces. @@ -30,7 +31,7 @@ server.on('listening', onListening); * Normalize a port into a number, string, or false. */ -function normalizePort(val) { +function normalizePort(val: string) { var port = parseInt(val, 10); if (isNaN(port)) { @@ -50,7 +51,7 @@ function normalizePort(val) { * Event listener for HTTP server "error" event. */ -function onError(error) { +function onError(error: { syscall: string; code: any; }) { if (error.syscall !== 'listen') { throw error; } @@ -80,6 +81,6 @@ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr - : 'port ' + addr.port; + : 'port ' + addr?.port; console.log('Web server listening on ' + bind); } \ No newline at end of file diff --git a/src/routes/api.ts b/src/routes/api.ts new file mode 100644 index 0000000..5119887 --- /dev/null +++ b/src/routes/api.ts @@ -0,0 +1,8 @@ +import { Router } from 'express'; +import { default as fileRouter } from '../controllers/files/api'; +const router = Router(); + +router.use('/files', fileRouter); +// router.use('/home') + +export default router; \ No newline at end of file diff --git a/utils/auth_utils.js b/src/utils/auth_utils.js similarity index 100% rename from utils/auth_utils.js rename to src/utils/auth_utils.js diff --git a/utils/db.js b/src/utils/db.js similarity index 100% rename from utils/db.js rename to src/utils/db.js diff --git a/utils/db_api.md b/src/utils/db_api.md similarity index 100% rename from utils/db_api.md rename to src/utils/db_api.md diff --git a/utils/db_utils.js b/src/utils/db_utils.js similarity index 100% rename from utils/db_utils.js rename to src/utils/db_utils.js diff --git a/utils/test/test_db.js b/src/utils/test/test_db.js similarity index 100% rename from utils/test/test_db.js rename to src/utils/test/test_db.js diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..76d4440 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,109 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": ["src/**/*", "server.ts"] +} diff --git a/utils.js b/utils.js deleted file mode 100644 index 6010702..0000000 --- a/utils.js +++ /dev/null @@ -1,52 +0,0 @@ -const path = require('path'); -const fs = require('fs'); -require('dotenv').config(); - -utils = {}; -utils.ROOT_PATH = path.resolve(__dirname); - utils.VIEWS_PATH = path.resolve(utils.ROOT_PATH, 'views'); - utils.DATA_PATH = path.resolve(utils.ROOT_PATH, 'dist/data'); - utils.DATA_JSON_PATH = path.resolve(utils.DATA_PATH, 'json'); - utils.DATA_DB_PATH = path.resolve(utils.DATA_PATH, 'db'); - utils.DATA_CONFIG_PATH = path.resolve(utils.DATA_PATH, 'config'); - utils.DATA_FILE_PATH = path.resolve(utils.DATA_PATH, 'file'); - -// 检查并创建路径 -[utils.DATA_PATH, utils.DATA_JSON_PATH, utils.DATA_DB_PATH, utils.DATA_CONFIG_PATH, utils.DATA_FILE_PATH].forEach((p) => { - if (!fs.existsSync(p)) { - fs.mkdirSync(p, { recursive: true }); - } -}); - -utils.json = { - success: { - code: '0000', - msg: 'success', - data: null - }, - error: { - code: '0001', - msg: 'unknown error', - data: null - }, - token_is_invalid: { - code: '0002', - msg: 'token invalid', - data: null - }, - user_is_invalid: { - code: '0100', - msg: 'login error', - data: null - }, - user_register_is_invalid: { - code: '0102', - msg: 'register error', - data: null - }, -} - -utils.path = path; -utils.fs = fs; -utils.env = process.env; -module.exports = utils; \ No newline at end of file