Commit c6034ba9 authored by wmvm's avatar wmvm

init

parents
# https://editorconfig.org
root = true # 已经是顶层配置文件,不必继续向上搜索
[*]
charset = utf-8 # 编码字符集
[*.{js,jsx,ts,tsx,vue}]
indent_style = space #缩进空格
indent_size = 4 # 缩进 4 个空格
end_of_line = lf # 每行结尾换行符
insert_final_newline = false # 末尾不插入新行
ij_any_space_before_catch_left_brace = true
ij_any_special_else_if_treatment = true
ij_any_finally_on_new_line = true # finally 语句换行
ij_any_catch_on_new_line = true # catch 语句换行
ij_any_else_on_new_line = true # else 语句换行
ij_typescript_spaces_within_imports = true # import 两侧增加空格
ij_javascript_spaces_within_imports = true # import 两侧增加空格
ij_javascript_space_before_async_arrow_lparen = true
ij_typescript_space_before_async_arrow_lparen = true
ij_typescript_spaces_within_object_literal_braces = true # 对象左括号右侧增加空格
ij_javascript_spaces_within_object_literal_braces = true # 对象左括号右侧增加空格
#
ij_any_spaces_around_assignment_operators = true
# 赋值语句两侧增加空格
# ij_any_spaces_around_assignment_operators = true
ij_editorconfig_spaces_around_assignment_operators = true
# 属性之间加入空行
ij_any_blank_lines_around_field = 1
ij_any_blank_lines_around_field_in_interface = 1
ij_typescript_use_double_quotes = true # 双引号
ij_javascript_use_double_quotes = true # 双引号
trim_trailing_whitespace = true
max_line_length = 160
# new_line= true
# ij_any_keep_simple_methods_in_one_line = true
# ij_any_keep_simple_blocks_in_one_line = true
# ij_typescript_keep_simple_blocks_in_one_line = true
# ij_any_call_parameters_wrap = on_every_item
# ij_any_align_multiline_parameters_in_calls = false
# ij_any_call_parameters_right_paren_on_new_line = false
# max_line_length = 1000
# max_line_length = off
# max_line_length = 1550
# ij_typescript_enforce_trailing_comma = remove
# ij_javascript_enforce_trailing_comma = remove
ij_json_keep_trailing_comma = false
ij_json_wrap_long_lines = true
ij_typescript_methods_wrap = before-first-and-after-last
ij_javascript_methods_wrap = before-first-and-after-last
node_modules
src/config/config.prod.js
.idea
build
1. dao / common 等基础库和 js 使用同一套,后续基础库都用 ts 重构
2. 业务服务等先保持和 js 风格相同
ts 代码启动方式
启动方式一,webstorm 直接启动 (jetBrain 系列应该都可以启动)
1. 安装插件 run configuration for typescript
![img.png](docs/img.png)
2. 在任意 ts 文件中右键可以执行或 debug ts 代码
![img.png](docs/img2.png)
import express, { Request, Response, NextFunction } from 'express';
import errorHandler from 'errorhandler';
import morgan from 'morgan';
import { logger, expressSetting } from '@broker/nodejs_common';
import appConfig from "./src/config";
import { apiRouterV1 } from "./src/router/v1";
const app = express();
expressSetting(app);
app.use(morgan('dev'));
if (appConfig.node_env === 'development') {
app.use(errorHandler());
}
else {
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
res.status(500).send("500 error");
});
}
app.use('/demo/v1', apiRouterV1);
app.listen(appConfig.port, '0.0.0.0', () => {
logger.info(
'MyToken-(api) server listening on %d, in %s mode',
appConfig.port,
app.get('env'),
);
});
This diff is collapsed.
{
"name": "mytoken-contract-api",
"version": "1.0.0",
"description": "nodejs 代码。 功能:用于合约数据业务层接口。",
"main": "index.ts",
"scripts": {
"build": "rm -rf build && tsc",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "ssh://git@gitlab.mytoken.org:10022/debin/mytoken-contract-api.git"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "1.0.2",
"@types/async": "3.2.24",
"@types/body-parser": "1.19.5",
"@types/cors": "2.8.17",
"@types/get-port": "4.2.0",
"@types/mongodb": "4.0.7",
"@types/node": "^20.11.30",
"@types/reflect-metadata": "0.1.0",
"@types/sequelize": "^4.28.20",
"@types/url-join": "4.0.3",
"@typescript-eslint/eslint-plugin": "7.4.0",
"@typescript-eslint/experimental-utils": "5.62.0",
"@typescript-eslint/parser": "7.4.0",
"eslint": "8.57.0",
"eslint-formatter-autolinkable-stylish": "1.3.0",
"eslint-plugin-import": "2.29.1",
"eslint-plugin-no-null": "1.0.2",
"nyc": "15.1.0",
"source-map-support": "0.5.21",
"ts-node": "10.9.2",
"typedoc": "0.25.12",
"typedoc-plugin-markdown": "3.17.1",
"typescript": "^5.4.3"
},
"dependencies": {
"@broker/nodejs_common": "git+ssh://git@gitlab.mytoken.org:10022/debin/broker-nodejs-common.git",
"@broker/nodejs_dao": "git+ssh://git@gitlab.mytoken.org:10022/debin/broker-nodejs-dao.git",
"@broker/nodejs_dao_next": "1.0.3",
"@types/errorhandler": "^1.5.3",
"@types/express": "^4.17.21",
"@types/morgan": "^1.9.9",
"axios": "1.7.2",
"errorhandler": "^1.5.1",
"express": "^4.18.2",
"glob": "10.3.10",
"lodash": "^4.17.21",
"moment": "^2.30.1",
"morgan": "^1.10.0",
"mysql2": "^1.7.0",
"node-schedule": "^2.1.1",
"rate-limiter-flexible": "^5.0.3",
"reflect-metadata": "0.2.2",
"sequelize": "^4.44.4",
"tunnel": "^0.0.6",
"uuid": "9.0.1"
}
}
// 配置文件暂时和 js 的导出方式保持一致,涉及到线上环境变量的替换等
module.exports = {};
\ No newline at end of file
// 配置文件暂时和 js 的导出方式保持一致,涉及到线上环境变量的替换等
module.exports = {
}
\ No newline at end of file
// 配置文件暂时和 js 的导出方式保持一致,涉及到线上环境变量的替换等
import _ from 'lodash';
const env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';
const config_file = './config.' + env;
const common_config = require('@broker/nodejs_common').config;
export default _.merge(
{
env
},
require(config_file),
common_config,
{
port: 8080, //服务端口
contractData: {}
}
);
\ No newline at end of file
{
"customBaseDir" :"/var/tmp/mytoken/",
"customDefaultAtt" :{
"type": "file",
"maxLogSize": "10M",
"backups": 5,
"alwaysIncludePattern": true
},
"appenders": {
"console": {"type": "console"},
"debug": {"filename": "debug/debug.log"},
"info": {"filename": "info/info.log"},
"warn": {"filename": "warn/warn.log"},
"error": {"filename": "error/error.log"}
},
"categories": {
"default": { "appenders": ["debug", "console"], "level": "debug" },
"infoLog": { "appenders": ["info", "console"], "level": "info" },
"warnLog": { "appenders": ["warn", "console"], "level": "warn" },
"errorLog":{ "appenders": ["error", "console"], "level": "error" }
},
"replaceConsole": true
}
\ No newline at end of file
import * as userService from "../service/user.service";
import { UserPayload } from "../service/user.service";
export const getUserInfo = async (req, payload: UserPayload) => {
return userService.getUserInfo(payload);
};
\ No newline at end of file
// ts 库
import { user } from "@broker/nodejs_dao_next";
// 可以直接引用原有 js 封装的工具, 但是目前 js 的库没有类型提示
// 后面吧 common 用 ts 改一下就行了
import { redisUtils } from "@broker/nodejs_common";
export interface UserPayload {
email: string;
name: string;
user_id: string;
}
export const getUserInfo = async (payload: UserPayload) => {
const key = "ts-api-demo:user"
const result = await redisUtils.getSync(key)
if (result) {
return {
user: result
}
}
const dbUser = await user.prototype.findOne({
where: {
id: payload.user_id
},
raw: true
});
if (dbUser) {
await redisUtils.writeSync(key, dbUser, 5)
}
return {
user: dbUser
}
};
import Express from "express"
const router = Express.Router();
const { logger, responsedata, errorCodeConst: errCode, errorCodeDefine } = require('@broker/nodejs_common');
const { getError, isValidResponseData } = responsedata;
import * as userController from "../../mvc/control/user.control"
const getFunc = {
'user/info': userController.getUserInfo,
};
const postFunc = {};
// TODO 这里先和 nodejs 的注册路由方式保持一样,后面在调整。
router.get('/*', (req, res, next) => {
let path = req.path ? req.path.slice(1) : '';
if (!path) {
return res.json(getError(errCode.CODE_NEED_ROUTER));
}
if (!getFunc[path]) {
return res.json(getError(errCode.CODE_UNDEFINE_ROUTER));
}
doJob(req, res, next, req.query, getFunc[path]);
});
router.post('/*', (req, res, next) => {
const path = req.path ? req.path.slice(1) : '';
if (!path) {
return res.json(getError(errCode.CODE_NEED_ROUTER));
}
if (!postFunc[path]) {
return res.json(getError(errCode.CODE_UNDEFINE_ROUTER));
}
doJob(req, res, next, req.body, postFunc[path]);
});
const doJob = (req, res, next, param, func) => {
let _func_name_ = 'router.doJob';
func(req, param).then(data => {
res.json(data);
}).catch(err => { // 可以抛出错误码
logger.warn(_func_name_, err);
if (isValidResponseData(err)) {
res.json(err);
return;
}
if (!err || !errorCodeDefine[err]) {
err = errCode.CODE_INTERNAL;
}
res.json(getError(err));
});
};
export const apiRouterV1 = router;
/**
* 测试 js 项目引用 ts 的 dao
*/
const { user } = require("@broker/nodejs_dao_next");
async function main() {
const dbUser = await user.prototype.findOne({
where: {
id: 1
},
raw: true
});
console.log(dbUser)
}
main()
.then(() => {
process.exit(0)
})
.catch((e) => {
console.error(e);
process.exit(1)
});
\ No newline at end of file
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2018", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [
"dom",
"dom.iterable"
],
"noImplicitAny": false,
"noImplicitOverride": true,
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": false, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./build", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
"types": ["mocha","node", "reflect-metadata"], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
"experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": [
"node_modules",
"build",
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment