js - fastify的基本使用
访问量: 783
refer to: https://www.fastify.io/
安装
npm install --global fastify-cli
生成框架文件:
fastify generate myproject
generated README.md generated plugins/README.md generated test/helper.js generated .gitignore generated app.js generated routes/README.md generated plugins/sensible.js generated plugins/support.js generated routes/example/index.js generated test/plugins/support.test.js generated routes/root.js generated test/routes/example.test.js generated test/routes/root.test.js --> reading package.json in airdrop-worker2 edited package.json, saving saved package.json --> project airdrop-worker2 generated successfully run 'npm install' to install the dependencies run 'npm start' to start the application run 'npm run dev' to start the application with pino-colada pretty logging (not suitable for production) run 'npm test' to execute the unit tests
example
server.get<{ Body: { name: string } }>("/rede/checkOwner", async function (request, reply) {
let name = request.body.name;
let res = await getOwner(name);
return { result: "ok", res: res };
});
日志
配置:
const server = fastify({
logger: {
level: 'debug',
file: 'log/new_claim_fastify.log'
}
});
修改package.json;
"dependencies": {
"fastify": "^3.24.1",
"fastify-cors": "^6.0.2",
"pino-pretty": "^7.6.0", // 需要这个。
},
参考:https://getpino.io/#/docs/api?id=mergingobject
request.log.debug("=== message: %s , %d, %o", "hello", 123, {name: 'luelue'})
获得参数
从 post body 中 request.body.param1
从url 中: request.query.param2
集成Typescript
1. 需要一个tsconfig.json
{
"compilerOptions": {
"target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
"module": "commonjs", /* Specify what module code is generated. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
2. 修改package.json
{
"name": "xxx-worker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"run-script": "tsc -p tsconfig.json && node script.js",
"run-names": "tsc -p tsconfig.json && node script-names.js",
"run-names-lock": "tsc -p tsconfig.json && node script-name-lock.js",
"pretty": "prettier --config .prettierrc './**/*.ts' --write",
"build": "tsc -p tsconfig.json",
"dev": "tsc -p tsconfig.json && node index.js",
"start": "node index.js",
"buildtest": "npm run build && tap --only test/app.test.js --no-check-coverage",
"test": "TAP_DIAG=1 tap --only test/app.test.js --no-check-coverage"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@polkadot/util-crypto": "^9.4.1",
"@types/node": "^17.0.31",
"@types/tap": "^15.0.7",
"axios": "^0.27.2",
"buffer": "^6.0.3",
"dotenv": "^16.0.0",
"ethers": "^5.6.4",
"fast-csv": "^4.3.6",
"fastify": "^3.29.0",
"fastify-cors": "6.0.2",
"js-sha3": "^0.8.0",
"pino-pretty": "^7.6.1",
"prettier": "^2.6.2",
"tap": "^16.1.0",
"typescript": "^4.6.4"
}
}
3. 创建 index.ts
import { app } from "./app";
let port = process.env.PORT || 8081;
async function start() {
let server = await app();
server.listen(port, "0.0.0.0", async (err, address) => {
if (err) {
console.error("== we got error:")
console.error(err);
process.exit(1);
}
console.log(`Server listening at ${address}`);
});
}
start();
3. 创建 app.ts
import 'dotenv/config'
import { readFileSync } from "fs";
import axios from "axios";
import fastify from "fastify";
import * as cors from "fastify-cors";
export async function app() {
const server = fastify({
logger: {
level: 'debug'
}
});
server.register(cors.default, {
origin: "*",
});
server.get("/ping", async (request, reply) => {
return { data: "ok" };
});
return server;
}