UNPKG

1.87 kBPlain TextView Raw
1import fp from './plugin';
2import fastify, { FastifyPlugin } from 'fastify';
3import { expectError } from 'tsd'
4
5export interface TestOptions {
6 customNumber: number
7}
8
9export const testPluginWithOptions: FastifyPlugin<TestOptions> = fp(
10 function (fastify, options, _next) {
11 fastify.decorate('utility', () => options.customNumber)
12 },
13 '>=1'
14);
15
16export const testPluginWithCallback: FastifyPlugin<TestOptions> = fp(
17 function (fastify, _options, next) {
18 fastify.decorate('utility', () => { })
19 next();
20 return;
21 }
22)
23
24export const testPluginWithAsync = fp<TestOptions>(
25 async function (fastify, _options) {
26 fastify.decorate('utility', () => { })
27 },
28 {
29 fastify: '>=1',
30 name: 'TestPlugin',
31 decorators: {
32 request: ['log']
33 }
34 }
35);
36
37// Register with HTTP
38const server = fastify()
39
40server.register(testPluginWithOptions) // register expects a FastifyPlugin
41server.register(testPluginWithCallback, { customNumber: 2 })
42server.register(testPluginWithAsync, { customNumber: 3 })
43expectError(server.register(testPluginWithCallback, { })) // invalid options passed to plugin on registration
44expectError(server.register(testPluginWithAsync, { customNumber: '2' })) // invalid type in options passed to plugin on registration
45
46
47// Register with HTTP2
48const serverWithHttp2 = fastify({ http2: true });
49
50serverWithHttp2.register(testPluginWithOptions) // register expects a FastifyPlugin
51serverWithHttp2.register(testPluginWithCallback)
52expectError(serverWithHttp2.register({ no: 'plugin' })) // register only accept valid plugins
53expectError(serverWithHttp2.register(testPluginWithAsync, { logLevel: 'invalid-log-level' })) // register options need to be valid built in fastify options
54expectError(serverWithHttp2.register(testPluginWithAsync, { customNumber: 'not-a-number' })) // or valid custom options defined by plugin itself