1 | /**
|
2 | * Most type annotations in this file are not strictly necessary but are
|
3 | * included for this example.
|
4 | *
|
5 | * To run this example execute the following commands to install typescript,
|
6 | * transpile the code, and start the server:
|
7 | *
|
8 | * npm i -g typescript
|
9 | * tsc examples/typescript-server.ts --target es6 --module commonjs
|
10 | * node examples/typescript-server.js
|
11 | */
|
12 |
|
13 | import fastify, { FastifyInstance, RouteShorthandOptions } from '../fastify';
|
14 | import { Server, IncomingMessage, ServerResponse } from 'http';
|
15 |
|
16 | // Create an http server. We pass the relevant typings for our http version used.
|
17 | // By passing types we get correctly typed access to the underlying http objects in routes.
|
18 | // If using http2 we'd pass <http2.Http2Server, http2.Http2ServerRequest, http2.Http2ServerResponse>
|
19 | const server: FastifyInstance<
|
20 | Server,
|
21 | IncomingMessage,
|
22 | ServerResponse
|
23 | > = fastify({ logger: true });
|
24 |
|
25 | // Define interfaces for our request. We can create these automatically
|
26 | // off our JSON Schema files (See TypeScript.md) but for the purpose of this
|
27 | // example we manually define them.
|
28 | interface PingQuerystring {
|
29 | foo?: number;
|
30 | }
|
31 |
|
32 | interface PingParams {
|
33 | bar?: string;
|
34 | }
|
35 |
|
36 | interface PingHeaders {
|
37 | a?: string;
|
38 | }
|
39 |
|
40 | interface PingBody {
|
41 | baz?: string;
|
42 | }
|
43 |
|
44 | // Define our route options with schema validation
|
45 | const opts: RouteShorthandOptions = {
|
46 | schema: {
|
47 | body: {
|
48 | type: 'object',
|
49 | properties: {
|
50 | pong: {
|
51 | type: 'string'
|
52 | }
|
53 | }
|
54 | }
|
55 | }
|
56 | };
|
57 |
|
58 | // Add our route handler with correct types
|
59 | server.post<{
|
60 | Querystring: PingQuerystring;
|
61 | Params: PingParams;
|
62 | Headers: PingHeaders;
|
63 | Body: PingBody;
|
64 | }>('/ping/:bar', opts, (request, reply) => {
|
65 | console.log(request.query); // this is of type `PingQuerystring`
|
66 | console.log(request.params); // this is of type `PingParams`
|
67 | console.log(request.headers); // this is of type `PingHeaders`
|
68 | console.log(request.body); // this is of type `PingBody`
|
69 | reply.code(200).send({ pong: 'it worked!' });
|
70 | });
|
71 |
|
72 | // Start your server
|
73 | server.listen({ port: 8080 }, (err, address) => {
|
74 | if (err) {
|
75 | console.error(err);
|
76 | process.exit(1);
|
77 | }
|
78 | console.log(`server listening on ${address}`)
|
79 | });
|
80 |
|
\ | No newline at end of file |