Untitled
unknown
javascript
a year ago
3.3 kB
8
Indexable
import {fastify} from "fastify";
import * as fs from "fs/promises";
import {createCatSchema} from "./schemas.js";
const serverOptions = {
logger: {
level: 'debug',
transport: {
target: 'pino-pretty'
}
},
// disableRequestLogging: true, // disables request/reply logging
// requestIdLogLabel: 'reqIdPO', // let's u set a custom name for the requestIdLog label
requestIdHeader: 'request-id', // tell's fastify to look at the request-id header, if there's no request id header it creates a new req Id
genReqId: function (httpIncomingMessage) { // the function that generates requestIds according to your app needs
return `lmao-${Math.random()}`
}
}
const app = fastify(serverOptions)
app.addHook('onRoute', function inspector(routeOptions){
console.log(routeOptions)
})
app.addHook('onRegister', function inspector(plugin, pluginOptions) {
console.log('Chapter 2, Plugin system and Boot process')
})
app.addHook('onReady', async function preLoading() {
console.log('async onReady')
})
app.addHook('onClose', async function manageClose(){
console.log('async onClose')
})
// endpoints
function business (request, reply) {
reply.send({helloFrom: this.server.address()})
}
async function foo(req, res) {
return {one: 1}
}
async function bar (req, res) {
const oneResponse = await foo(req, res)
return {
one: oneResponse,
two: 2
}
}
app.get('/', async (request, reply) => {
return { hello: 'world' }
})
app.route({
url: '/hello',
method: 'GET',
handler: function myHandler (request, reply) {
reply.send('world')
}
})
app.get('/multi-async', bar)
app.get('/server', business)
app.get('/multi', (req, reply) => {
reply.send('one')
reply.send('two')
reply.send('three')
app.log.info('this line is executed')
})
app.get('/file', function promiseHandler(req, res) {
const fileName = './package.json'
return fs.readFile(fileName, {
encoding: 'utf8'
})
})
const cats = []
app.post('/cats', {
schema: {
body: createCatSchema
}
},(req, res) => {
cats.push(req.body)
res.code(201).send({cats})
})
app.get('/xray', (req) => {
return {
id: req.id, // id assigned to the request in req-progress
ip: req.ip, // the client ip address
ips: req.ips, // proxy ip address
hostname: req.hostname,
protocol: req.protocol,
method: req.method,
url: req.url,
routerPath: req.routerPath,
is404: req.is404
}
})
app.get('/cats/:cat_name', (req, res) => {
const {cat_name: catName} = req.params
const cat = cats.find((cat) => cat.name === catName)
if (!cat) {
res.code('404')
throw new Error(`cat ${catName} not found`)
}
res.code(200)
return cat
})
app.get('/log', (req, res) => {
// req.log.info('hello')
// req.log.info('world')
//
// res.log.info('late for the party')
// app.log.info('unrelated')
res.send()
})
await app.listen({
port: 8080,
host: '0.0.0.0'
}
)
app.log.debug(app.initialConfig, 'fastify listening with the config')
const { port } = app.server.address()
app.log.info(`Using port ${port}`)Editor is loading...
Leave a Comment