Repository navigation
Expand file tree
/
Copy pathmain.tsp
More file actions
397 lines (342 loc) · 9.16 KB
/
Copy pathmain.tsp
File metadata and controls
397 lines (342 loc) · 9.16 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import "@typespec/http";
import "@typespec/rest";
import "@typespec/versioning";
import "@typespec/openapi3";
import "@typespec/openapi";
using TypeSpec.Versioning;
using TypeSpec.Http;
using TypeSpec.OpenAPI;
@service(#{ title: "Rest API Example" })
@info(#{
license: #{
name: "ISC",
url: "https://opensource.org/license/isc-license-txt",
},
})
@server("http://localhost:3000", "Локальная разработка")
@versioned(Versions)
namespace FastifyRestApiExample;
enum Versions {
v1,
v2,
}
/**
* https://www.rfc-editor.org/rfc/rfc9457.html
*/
@error
model ProblemDetails {
@header("content-type") contentType: "application/problem+json";
type?: string;
title?: string;
status?: integer;
detail?: string;
instance?: string;
}
@error
model BadRequestError {
@statusCode _: 400;
...ProblemDetails;
}
@error
model TooManyRequestsError {
@statusCode _: 429;
...ProblemDetails;
}
// Эти два исхода возможны почти везде: 400 отдаёт валидация запроса по этой же
// спеке, 429 — ограничитель частоты. Раньше их не было в контракте вовсе, и
// клиент по спеке не мог их предусмотреть.
alias CommonErrors = BadRequestError | TooManyRequestsError;
@error
model ConflictError {
@statusCode _: 409;
...ProblemDetails;
}
@error
model PreconditionFailedError {
@statusCode _: 412;
...ProblemDetails;
}
@error
model NotFoundError {
@statusCode _: 404;
...ProblemDetails;
}
@error
model UnauthorizedError {
@statusCode _: 401;
...ProblemDetails;
}
@error
model ForbiddenError {
@statusCode _: 403;
...ProblemDetails;
}
@error
model UnprocessableEntityError {
@statusCode _: 422;
...ProblemDetails;
errors: Array<{
message: string;
rule: string;
field: string;
}>;
}
// Ответ списка сообщает, где клиент находится и сколько всего есть. Без этого
// page уходил в запрос, а обратно не возвращалось ничего: узнать, есть ли
// следующая страница, было нельзя.
model PageMeta {
page: int32;
perPage: int32;
total: int32;
totalPages: int32;
}
model Timestamps {
// createdAt: utcDateTime;
}
model User {
id: numeric;
@minLength(2)
@maxLength(100)
fullName: string | null;
// Nullable, а не необязательное: колонка добавляется существующей таблице, и
// NOT NULL там упёрся бы в уже лежащие строки — как было с password_digest.
@added(Versions.v2) phone: string | null;
// @format("email")
email: string;
...Timestamps;
}
model UserCreateDTO {
// Границы те же, что у User: иначе запрос принимает имя, которое валидатор
// ответа потом забракует, и создание падает в 500.
@minLength(2)
@maxLength(100)
fullName?: string;
email: string;
@minLength(8)
@secret
password: string;
@added(Versions.v2) phone?: string;
}
model UserEditDTO {
@minLength(2)
@maxLength(100)
fullName?: string;
@minLength(8)
@secret
password?: string;
@added(Versions.v2) phone?: string;
}
model Course {
id: numeric;
name: string;
description: string;
...Timestamps;
}
model CourseCreateDTO {
name: string;
description: string;
}
model CourseEditDTO {
name?: string;
description?: string;
}
model CourseLesson {
id: numeric;
courseId: numeric;
name: string;
body: string;
...Timestamps;
}
model AuthInfo {
email: string;
@secret
password: string;
}
model TokenInfo {
token: string;
}
model CourseLessonCreateDTO {
name: string;
body: string;
}
model CourseLessonEditDTO {
name?: string;
body?: string;
}
@route("/users")
namespace users {
@summary("Список пользователей")
@operationId("usersIndex")
@get
@useAuth(BearerAuth)
op index(
@query @minValue(1) page?: int32 = 1,
@query @minValue(1) @maxValue(100) perPage?: int32 = 10,
): {
@body users: {
data: User[];
meta: PageMeta;
};
} | UnauthorizedError | CommonErrors;
@summary("Пользователь по идентификатору")
@get
@useAuth(BearerAuth)
@operationId("usersShow")
op show(@path @minValue(1) id: int32): {
@body _: User;
} | NotFoundError | UnauthorizedError | CommonErrors;
@summary("Регистрация пользователя")
@post
@operationId("usersCreate")
op create(@body _: UserCreateDTO): {
@body _: User;
@statusCode statusCode: 201;
} | UnprocessableEntityError | CommonErrors;
@summary("Изменение пользователя")
@put
@useAuth(BearerAuth)
@operationId("usersUpdate")
op update(@path @minValue(1) id: int32, @body user: UserEditDTO): {
@body user: User;
} | NotFoundError | UnprocessableEntityError | UnauthorizedError | CommonErrors;
@summary("Удаление пользователя")
@delete
@useAuth(BearerAuth)
@operationId("usersDestroy")
op destroy(@path @minValue(1) id: int32): {
@statusCode statusCode: 204;
} | NotFoundError | UnauthorizedError | ConflictError | CommonErrors;
}
@route("/tokens")
namespace tokens {
@summary("Выдача токена по email и паролю")
@post
@operationId("tokensCreate")
op create(@body auth_info: AuthInfo): {
@body token: TokenInfo;
@statusCode statusCode: 201;
} | UnprocessableEntityError | UnauthorizedError | CommonErrors;
}
@route("/courses")
namespace courses {
@summary("Список курсов")
@get
@operationId("coursesIndex")
op index(
@query @minValue(1) page?: int32 = 1,
@query @minValue(1) @maxValue(100) perPage?: int32 = 10,
): {
@body courses: {
data: Course[];
meta: PageMeta;
};
} | CommonErrors;
@summary("Курс по идентификатору")
@get
@operationId("coursesShow")
op show(@path @minValue(1) id: int32): {
@body course: Course;
} | NotFoundError | CommonErrors;
@summary("Создание курса")
@post
@useAuth(BearerAuth)
@operationId("coursesCreate")
op create(@body course: CourseCreateDTO): {
@body course: Course;
@statusCode statusCode: 201;
} | UnprocessableEntityError | UnauthorizedError | CommonErrors;
@summary("Изменение курса")
@put
@useAuth(BearerAuth)
@operationId("coursesUpdate")
op update(
@path @minValue(1) id: int32,
@body course: CourseEditDTO,
/**
* ETag из предыдущего GET. Необязателен; если прислан и запись с тех пор
* изменилась, правка отклоняется с 412.
*/
@header("If-Match") ifMatch?: string,
):
| {
@body course: Course;
}
| NotFoundError
| UnprocessableEntityError
| UnauthorizedError
| ForbiddenError
| PreconditionFailedError
| CommonErrors;
@summary("Удаление курса")
@delete
@useAuth(BearerAuth)
@operationId("coursesDestroy")
op destroy(
@path @minValue(1) id: int32,
/** ETag из предыдущего GET; см. update. */
@header("If-Match") ifMatch?: string,
):
| {
@statusCode statusCode: 204;
}
| NotFoundError
| UnauthorizedError
| ForbiddenError
| PreconditionFailedError
| CommonErrors;
}
@route("/courses/{courseId}/lessons")
namespace courses_lessons {
@summary("Список уроков курса")
@get
@operationId("coursesLessonsIndex")
op index(
@path @minValue(1) courseId: int32,
@query @minValue(1) page?: int32 = 1,
@query @minValue(1) @maxValue(100) perPage?: int32 = 10,
): {
@body lessons: {
data: CourseLesson[];
meta: PageMeta;
};
} | CommonErrors;
@summary("Урок курса")
@get
@operationId("coursesLessonsShow")
op show(@path @minValue(1) courseId: int32, @path @minValue(1) id: int32): {
@body lessons: CourseLesson;
} | NotFoundError | CommonErrors;
@summary("Добавление урока в курс")
@post
@useAuth(BearerAuth)
@operationId("coursesLessonsCreate")
op create(@path @minValue(1) courseId: int32, @body course: CourseLessonCreateDTO): {
@body lesson: CourseLesson;
@statusCode statusCode: 201;
} | UnprocessableEntityError | UnauthorizedError | ForbiddenError | NotFoundError | CommonErrors;
@summary("Изменение урока")
@put
@useAuth(BearerAuth)
@operationId("coursesLessonsUpdate")
op update(
@path @minValue(1) courseId: int32,
@path @minValue(1) id: int32,
@body lesson: CourseLessonEditDTO,
):
| {
@body lesson: CourseLesson;
}
| NotFoundError
| UnprocessableEntityError
| UnauthorizedError
| ForbiddenError
| PreconditionFailedError
| CommonErrors;
@summary("Удаление урока")
@delete
@useAuth(BearerAuth)
@operationId("coursesLessonsDestroy")
op destroy(@path @minValue(1) courseId: int32, @path @minValue(1) id: int32): {
@statusCode statusCode: 204;
} | NotFoundError | UnauthorizedError | ForbiddenError | CommonErrors;
}