feat(server): 添加类型定义和支持TypeScript的配置

已更新package.json以包含TypeScript编译步骤,并添加了对Express和Node.js的类型定义。这允许在项目中使用TypeScript编写代码,提供了更强的类型检查和更好的IDE集成体验。

此外,已删除多个不再需要的Node.js脚本和过时的控制器、服务和实用程序文件,以简化代码库并为其向TypeScript的迁移做准备。
This commit is contained in:
ZZY 2024-08-25 22:35:10 +08:00
parent 510a33489f
commit e3ead37760
22 changed files with 197 additions and 145 deletions

View File

@ -2,31 +2,40 @@
## [Version 1.0.0] - 2024-04-11 ## [Version 1.0.0] - 2024-04-11
### History - History
0. 较于曾今版本重新开发由于安全问题重新启用git。 1. 较于曾今版本重新开发由于安全问题重新启用git。
1. 修改了静态网页的代码并使用booststrap框架和anchor模板。 2. 修改了静态网页的代码并使用booststrap框架和anchor模板。
2. 对于曾经的express框架对代码进行重构。 3. 对于曾经的express框架对代码进行重构。
3. 使用了dotenv模块加载配置项。 4. 使用了dotenv模块加载配置项。
4. 修改部分文件架构尤其是各类隐藏文件夹。 5. 修改部分文件架构尤其是各类隐藏文件夹。
## [Version 1.0.1-alpha] - 2024-04-13 ## [Version 1.0.1-alpha] - 2024-04-13
### New Features - New Features
0. 大量修改文件结构详情见README.md。 1. 大量修改文件结构详情见README.md。
1. 添加了登录,注册,管理员的功能。 2. 添加了登录,注册,管理员的功能。
2. 使用better-sqlite3重构数据库接口。 3. 使用better-sqlite3重构数据库接口。
3. 重构代码结构使其路由更清晰更易于使用cookie(未来将会重构cookie代码)。 4. 重构代码结构使其路由更清晰更易于使用cookie(未来将会重构cookie代码)。
4. 添加VERSION.md文件记录版本历史。 5. 添加VERSION.md文件记录版本历史。
5. 添加各种细节。 6. 添加各种细节。
### Bugs Fixed - Bugs Fixed
1. 修改default.env文件使其初始化密码简易包括硬性写入代码中的密码(default.env文件就是代码内的各项参数的默认值)。 1. 修改default.env文件使其初始化密码简易包括硬性写入代码中的密码(default.env文件就是代码内的各项参数的默认值)。
## [Version 1.1.0-alpha] - 2024-06-02 ~ 2024-07-23 ## [Version 1.1.0-alpha] - 2024-06-02 ~ 2024-07-23
### New Features - New Features
1. 重构代码使用Vue3重构前端。 1. 重构代码使用Vue3重构前端。
2. 禁用登录功能。
3. 根据API修改文件读取。
## [Version 1.1.0-beta] - 2024-08
- New Features
1. 使用typescript重构代码。
2. 修改VERSION.md文件。

View File

@ -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;

View File

@ -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 };

View File

@ -2,10 +2,11 @@
"name": "web_zzyxyz", "name": "web_zzyxyz",
"version": "1.0.1", "version": "1.0.1",
"description": "None", "description": "None",
"main": "./main/web.js",
"scripts": { "scripts": {
"test": "nodemon ./main/web.js", "build": "tsc && node ./dist/src/main.js",
"start": "node ./main/web.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", "author": "zzy",
"license": "ISC", "license": "ISC",
@ -15,7 +16,13 @@
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"nodemon": "^3.1.0",
"ws": "^8.17.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"
} }
} }

View File

@ -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;

View File

@ -1,19 +1,22 @@
const express = require('express'); import express, { Application, Request, Response, NextFunction } from 'express';
const path = require('path'); import path from 'path';
require('dotenv').config(); import dotenv from 'dotenv';
env = process.env; 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.json());
app.use(express.urlencoded({ extended: false })); app.use(express.urlencoded({ extended: false }));
app.use(require('cookie-parser')()); app.use(require('cookie-parser')());
dist = path.join(__dirname, env.STATIC_PATH ?? 'static') const dist = path.join(__dirname, env.STATIC_PATH ?? 'static');
// 静态资源服务假设你的dist目录包含了编译后的Vue应用 // 静态资源服务假设你的dist目录包含了编译后的Vue应用
app.use(express.static(dist)); 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 // // catch 404 and forward to error handler
// app.use(function(req, res, next) { // app.use(function(req, res, next) {
@ -22,12 +25,12 @@ app.use('/api', require('./routes/api.js'));
// }); // });
// 所有未匹配到的请求都重定向到index.html,使用vue3的SPA匹配 // 所有未匹配到的请求都重定向到index.html,使用vue3的SPA匹配
app.get('*', (req, res) => { app.get('*', (req: Request, res: Response) => {
res.sendFile(path.join(dist, '/index.html')); res.sendFile(path.join(dist, '/index.html'));
}); });
// error handler // 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 // set locals, only providing error in development
res.locals.message = err.message; res.locals.message = err.message;
res.locals.error = env.MOD === 'development' ? err : {}; res.locals.error = env.MOD === 'development' ? err : {};
@ -36,6 +39,4 @@ app.use(function(err, req, res, next) {
// render the error page // render the error page
res.status(err.status || 500); res.status(err.status || 500);
res.end('<h1>error</h1>'); res.end('<h1>error</h1>');
}); });
module.exports = app;

View File

@ -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 };

View File

@ -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;

View File

@ -1,11 +1,9 @@
const {join} = require('path'); import { join } from 'path';
const fs = require('fs'); import fs from 'fs';
require('dotenv').config(); const root = join(__dirname, '../../../');
const env = process.env;
const root = join(__dirname, '../../');
function getFilePath(path) { export function getFilePath(path: string) {
return join(root, `${env.FILE_PATH}`, path); return join(`${process.env.ROOT_DIR}`, `${process.env.FILE_PATH}`, path);
} }
// function getFile(path, callback) { // function getFile(path, callback) {
@ -19,6 +17,4 @@ function getFilePath(path) {
// callback(data); // callback(data);
// }); // });
// } // }
module.exports = getFilePath;

View File

@ -1,7 +1,7 @@
const utils = require('../utils.js'); const utils = require('../utils.js');
const path = require('path'); const path = require('path');
const auth = require('../utils/auth_utils'); const auth = require('../../utils/auth_utils.js');
const db = require('../utils/db'); const db = require('../../utils/db.js');
db.createTable('users', [ db.createTable('users', [
{name :'id', type: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'}, {name :'id', type: 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'},

View File

@ -2,10 +2,11 @@
* Module dependencies. * Module dependencies.
*/ */
const app = require('../server.js'); import { app } from '../server';
const http = require('http'); import { createServer } from 'http';
require('dotenv').config(); import dotenv from 'dotenv';
env = process.env; dotenv.config();
const env = process.env;
/** /**
* Get port from config and store in Express. * Get port from config and store in Express.
@ -16,7 +17,7 @@ app.set('port', port);
/** /**
* Create HTTP server. * Create HTTP server.
*/ */
const server = http.createServer(app); const server = createServer(app);
/** /**
* Listen on provided port, on all network interfaces. * 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. * Normalize a port into a number, string, or false.
*/ */
function normalizePort(val) { function normalizePort(val: string) {
var port = parseInt(val, 10); var port = parseInt(val, 10);
if (isNaN(port)) { if (isNaN(port)) {
@ -50,7 +51,7 @@ function normalizePort(val) {
* Event listener for HTTP server "error" event. * Event listener for HTTP server "error" event.
*/ */
function onError(error) { function onError(error: { syscall: string; code: any; }) {
if (error.syscall !== 'listen') { if (error.syscall !== 'listen') {
throw error; throw error;
} }
@ -80,6 +81,6 @@ function onListening() {
var addr = server.address(); var addr = server.address();
var bind = typeof addr === 'string' var bind = typeof addr === 'string'
? 'pipe ' + addr ? 'pipe ' + addr
: 'port ' + addr.port; : 'port ' + addr?.port;
console.log('Web server listening on ' + bind); console.log('Web server listening on ' + bind);
} }

8
src/routes/api.ts Normal file
View File

@ -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;

109
tsconfig.json Normal file
View File

@ -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 '<reference>'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"]
}

View File

@ -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;