forked from elierotenberg/fastify-zod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.legacy.fixtures.ts
122 lines (110 loc) · 2.77 KB
/
server.legacy.fixtures.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import fastify, { FastifyInstance, FastifyServerOptions } from "fastify";
import fastifySwagger, { FastifyDynamicSwaggerOptions } from "@fastify/swagger";
import { NotFound, BadRequest } from "http-errors";
import { buildJsonSchemas, withRefResolver } from "..";
import { BuildJsonSchemasOptions } from "../JsonSchema";
import {
models,
TodoItem,
TodoItemId,
TodoItems,
TodoItemsGroupedByStatus,
} from "./models.fixtures";
export const createLegacyTestServer = (
fastifyOptions: FastifyServerOptions,
buildJsonSchemasOptions: BuildJsonSchemasOptions,
swaggerOptions: FastifyDynamicSwaggerOptions,
): FastifyInstance => {
const f = fastify(fastifyOptions);
f.register(fastifySwagger, withRefResolver(swaggerOptions));
const { $ref, schemas } = buildJsonSchemas(models, buildJsonSchemasOptions);
for (const schema of schemas) {
f.addSchema(schema);
}
const state: TodoItems = {
todoItems: [],
};
f.get<{
Reply: TodoItems;
}>(
`/item`,
{
schema: {
operationId: `getTodoItems`,
response: {
200: $ref(`TodoItems`),
},
},
},
async () => state,
);
f.get<{
Reply: TodoItemsGroupedByStatus;
}>(
`/item/grouped-by-status`,
{
schema: {
operationId: `getTodoItemsGroupedByStatus`,
response: {
200: $ref(`TodoItemsGroupedByStatus`),
},
},
},
async () => ({
done: state.todoItems.filter((item) => item.state === `done`),
inProgress: state.todoItems.filter(
(item) => item.state === `in progress`,
),
todo: state.todoItems.filter((item) => item.state === `todo`),
}),
);
f.post<{
Body: TodoItem;
Reply: TodoItems;
}>(
`/item`,
{
schema: {
operationId: `postTodoItem`,
body: $ref(`TodoItem`),
response: {
200: $ref(`TodoItems`),
},
},
},
async ({ body: nextItem }) => {
if (state.todoItems.some((prevItem) => prevItem.id === nextItem.id)) {
throw new BadRequest(`item already exists`);
}
state.todoItems = [...state.todoItems, nextItem];
return state;
},
);
f.put<{
Body: TodoItem;
Params: TodoItemId;
Reply: TodoItem;
}>(
`/item/:id`,
{
schema: {
operationId: `putTodoItem`,
body: $ref(`TodoItem`),
params: $ref(`TodoItemId`),
response: {
200: $ref(`TodoItem`),
},
},
},
async ({ params: { id }, body: nextItem }) => {
if (!state.todoItems.some((prevItem) => prevItem.id === id)) {
throw new NotFound(`no such item`);
}
state.todoItems = state.todoItems.map((prevItem) =>
prevItem.id === id ? nextItem : prevItem,
);
return nextItem;
},
);
return f;
};