Skip to main content

如何组织项目

秉持一切皆路由的原则。#

|   .gitignore|   index.ts                            入口文件,项目配置|   LICENSE|   package.json|   README.md|   tsconfig.json|\---src    +---database    \---routings                        路由        +---cat                         cat路由模块        |       cat.handler.ts          cat路由        |       cat.routing.ts          cat处理程序         |        +---dog        |       dog.handler.ts        |       dog.routing.ts        |        \---main                        cat路由模块                   main.handler.ts                main.routing.ts

采用路由,处理程序两级的模式,简单不失优雅。

路由书写规范#

路由将请求与处理程序结合。路由模块内一般不写业务逻辑,业务逻辑由handler处理,保持路由模块的简洁。

import { Response, Request, Module } from '@markstien/fly';import { mainHandler } from "./main.handler";
export const mainRouting: Module = {    getHello: {        path: '/',        method: 'GET',        handler: function (request: Request,response: Response) {            response.sendText('Hello,world!');        }    },    getUser: {        path: '/user',        method: 'GET',        handler: function (request: Request,response: Response) {            const user = mainHandler.getUser(request.params['id']);            response.sendText(JSON.stringify(user));        }    }}

处理程序书写规范#

处理程序书写具体业务逻辑,调用数据库模块封装的功能。

import db from './database';
interface User {    id: string;    name: string;    age: number;}
export const mainHandler = {    getUser(id: string): User {        return db.getUser(id);    }}