* Most type annotations in this file are not strictly necessary but are
* included for this example.
*
* To run this example execute the following commands to install typescript,
* transpile the code, and start the server:
*
* npm i -g typescript
* tsc examples/typescript-server.ts --target es6 --module commonjs
* node examples/typescript-server.js
*/
import fastify, { FastifyInstance, RouteShorthandOptions } from '../fastify'
import { Server, IncomingMessage, ServerResponse } from 'node:http'
const server: FastifyInstance<
Server,
IncomingMessage,
ServerResponse
> = fastify({ logger: true })
interface PingQuerystring {
foo?: number;
}
interface PingParams {
bar?: string;
}
interface PingHeaders {
a?: string;
}
interface PingBody {
baz?: string;
}
const opts: RouteShorthandOptions = {
schema: {
body: {
type: 'object',
properties: {
pong: {
type: 'string'
}
}
}
}
}
server.post<{
Querystring: PingQuerystring;
Params: PingParams;
Headers: PingHeaders;
Body: PingBody;
}>('/ping/:bar', opts, (request, reply) => {
console.log(request.query)
console.log(request.params)
console.log(request.headers)
console.log(request.body)
reply.code(200).send({ pong: 'it worked!' })
})
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`server listening on ${address}`)
})