npm i fastify-di fastify mysql typeorm
npm i typescript @types/node -D
- Folder Structure:
. ├── src │ ├── hello.controller.ts │ └── main.ts ├── package.json ├── server.config.js └── tsconfig.json
- Create configuration file:
// file server.config.js module.exports = { app: { env: 'development', port: 3000 }, database: { name: 'default', type: 'mysql', port: 3306, username: 'root', password: 'root', database: 'test', synchronize: true, logging: false } }
// file tsconfig.json { "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "target": "es6", "strict": true, "noImplicitAny": false, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", "jsx": "react", "emitDecoratorMetadata": true, "experimentalDecorators": true, "strictPropertyInitialization": false } }
- Create controller:
// file hello.controller.ts import { Controller, Get } from 'fastify-di' import { FastifyReply, FastifyRequest } from 'fastify' import { Http2ServerResponse } from 'http2' @Controller() export class HelloController { @Get() sayHello (request: FastifyRequest, reply: FastifyReply<Http2ServerResponse>): any { reply.send('hello') } }
- Create server:
// file main.ts import { createServer, start } from 'fastify-di' createServer() .then(server => { start(server) })
- Run server:
npx tsc
node dist/main.js
- Create Service
// file hello.service.ts import { Service } from 'fastify-di' @Service() export class HelloService { public sayHello (): string { return 'Hello' } }
- Inject service to controller & add hook
// file hello.controller.ts import { Controller, Get, InjectService, Hook } from 'fastify-di' import { FastifyReply, FastifyRequest } from 'fastify' import { Http2ServerResponse } from 'http2' import { HelloService } from './HelloService' @Controller() export class HelloController { @InjectService() service: HelloService @Get() sayHello (request: FastifyRequest, reply: FastifyReply<Http2ServerResponse>): void { const hello = this.service.sayHello() reply.send(hello) } }
// file hello.controller.ts
import { Controller, Get, InjectService, Hook } from 'fastify-di'
import { FastifyReply, FastifyRequest } from 'fastify'
import { Http2ServerResponse } from 'http2'
import { HelloService } from './HelloService'
@Controller()
export class HelloController {
@InjectService()
service: HelloService
@Get()
sayHello (request: FastifyRequest, reply: FastifyReply<Http2ServerResponse>): void {
const hello = this.service.sayHello()
reply.send(hello)
}
@Hook('onRequest')
async myHook (request: FastifyRequest, reply: FastifyReply<Http2ServerResponse>): Promise<void> {
// This hook will always be executed after the shared `onRequest` hooks
// Check this for detail: https://www.fastify.io/docs/latest/Hooks/#scope
console.log('request', request.headers)
}
}
- For more example, check this: https://github.com/ynwd/fastify-di-example