English | 中文
Functional API server for node.js base on Koa and TypeScript.
- API routing rules refer to functions, without configure routes, functions as a service.
- Support TypeScript and JavaScript, without manually compile, startup script is runing application directly.
- Packing application entry file for server startup, focus on business code.
$ npm i functional-api// index.ts
export default async (params, ctx) => {
return 'Hello Functional API';
};# startup server
$ functional-apiThe following mainly introduces the framework from the concepts of CLI, Config, Router, Functions, Params, Context:
Execute functional-api command to start the server, and functional-api --help to get the options info:
$ functional-api --help
Usage: functional-api [options]
Functional API Server
Options:
-p, --port <port> server port number (default: 20209)
-s, --src <directory> functions source directory path (default: ./ [the cwd path])
-c, --config <file> extend config file path (default: ./functional-api.config.ts [may not be provided])
--prod, --production whether to serve in production environmentYou can create ./functional-api.config.ts file under the startup path for configuration:
const config: FA.Config = {
port: 3000, // server port number, default: 20209
src: './functions', // unctions source directory path, default: ./
middlewares: [], // middlewares, globally loaded in order
context(ctx) {}, // context, can be injected
application(app) {}, // application, can be injected
/* configure the built-in middleware */
'koa-body': {}, // refer to koa-body documentation (default enabled text, json, urlencoded, multipart)
'koa-logger': {}, // refer to koa-logger documentation
};
export default config;The routing of the functional framework is fixed, and the specific rules are as follows:
/filepath:funcname?querystring
filepath: the relative path of the function file underconfig.src(satisfies therequire.resolverule)funcname: the name of the called function, the default value isdefaultquerystring: the url query string
Call the default export function:
- Request
/, or request/index- load theindex.tsfile and call the default exporteddefaultfunction - Request
/project/list- load theproject/list.tsfile and call the default exporteddefaultfunction
Call other export functions:
- Request
/:main- load theindex.tsfile and call the exportedmainfunction - Request
/user:get- load theuser.tsfile and call the exportedgetfunction - Request
/user/:get- load theuser/index.tsfile and call the exportedgetfunction
Each route refer to a function, supports async function or common function:
The function contains two parameters (params, ctx), they are described in detail below:
params: requestParamsvaluectx:Contextobject
The return value of the function call is returned as the response body, supporting the Object Array string Buffer Stream null data format, and it will define the corresponding default value for the response header Content-Type. In fact, it is assigned to koa ctx.response.body.
As the first parameter of the function, params means the parameter value carried in this request. According to the format of the request body, its value has two cases:
- If the request format is
jsonorform, thenparamsis the parsed and merged object of the request bodyctx.request.bodyand URL request parameterquerystring; - If the request format is
text,xmlor other formats, thenparamsis the content of the request bodyctx.request.body.
The
paramsparameter is mainly used to quickly obtain the requested value. If you want to get the details of the request body explicitly, you can usectx.requestin the context of the second parameter.
As the second parameter of the function, ctx means the context of this request. Since this functional framework is based on koa, the concept of Context comes from it. You can use context to achieve more capabilities:
ctxKoa Contextctx.requestKoa Requestctx.responseKoa Response
Since node.js does not support ES Module, you need to use the CommonJS to export:
exports.default = (params, ctx) => {
return params;
};
/* This example means to return the request parameter value, such as:
- GET /index?x=1&y=2 return { x: 1, y: 2 }
- POST /index?x=1&y=2 body { y: 0, z: 3 }
return { x: 1, y: 0, z: 3 }
*/It is recommended to practice TypeScript in functions. Before, you need to configure tsconfig.json for the entire project:
{
"extends": "functional-api/tsconfig",
"include": ["**/*", "*.*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}Of course, don't forget to install typescript for the project. Then you can write a function like the following, and define the request and response data format of the function:
export interface Req {
id?: string,
}
export interface Res {
code: number,
message: string,
data: { ... }
}
const main: FA.Function<Req, Res> = async (params, ctx): Promise<Res> => {
console.log(params.id);
return {
code: 0,
message: 'OK',
data: { ... },
};
};
export default main;export default async (params, ctx) => {
ctx.type = 'application/xml';
return `<xml>${params}</xml>`
};