UNPKG

1.33 kBPlain TextView Raw
1
2/**
3 * Most type annotations in this file are not strictly necessary but are
4 * included for this example.
5 *
6 * To run this example execute the following commands to install typescript,
7 * transpile the code, and start the server:
8 *
9 * npm i -g typescript
10 * tsc examples/typescript-server.ts --target es6 --module commonjs
11 * node examples/typescript-server.js
12 */
13
14import * as fastify from '../fastify'
15import * as cors from 'cors'
16import { createReadStream } from 'fs'
17import * as http from 'http'
18
19const server = fastify()
20
21const opts = {
22 schema: {
23 response: {
24 200: {
25 type: 'object',
26 properties: {
27 hello: {
28 type: 'string'
29 }
30 }
31 }
32 }
33 }
34}
35
36function getHelloHandler (req: fastify.FastifyRequest<http.IncomingMessage>,
37 reply: fastify.FastifyReply<http.ServerResponse>) {
38 reply.header('Content-Type', 'application/json').code(200)
39 reply.send({ hello: 'world' })
40}
41
42function getStreamHandler (req, reply) {
43 const stream = createReadStream(process.cwd() + '/examples/plugin.js', 'utf8')
44 reply.code(200).send(stream)
45}
46
47server.use(cors())
48server.get('/', opts, getHelloHandler)
49server.get('/stream', getStreamHandler)
50
51server.listen(3000, err => {
52 if (err) throw err
53 console.log(`server listening on ${server.server.address().port}`)
54})