-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
81 lines (76 loc) · 1.9 KB
/
server.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
import {
ParseResult,
object,
string,
int,
optional,
array,
id,
values,
} from 'cast.ts'
import express from 'express'
import { print } from 'listening-on'
let app = express()
let port = 8100
app.listen(port, () => {
print(port)
})
let searchQuery = object({
page: optional(int({ min: 1 })),
count: optional(int({ max: 25 })),
cat: optional(array(id(), { maybeSingle: true })),
keyword: string({ minLength: 3 }),
color: optional(
values([
'red' as const,
'yellow' as const,
'green' as const,
'blue' as const,
]),
),
})
type SearchQuery = ParseResult<typeof searchQuery>
// The inferred type is {
// page: number | undefined
// count: number | undefined
// cat: number[] | undefined
// keyword: string
// color: "red" | "yellow" | "green" | "blue" | undefined
// }
// Example: http://localhost:8100/product/search?page=2&count=20&keyword=food&cat=12&cat=18
app.get('/product/search', async (req, res) => {
let query: SearchQuery
try {
console.log(req.method, req.url, req.query)
query = searchQuery.parse(req.query)
console.log('parsed query:', query)
} catch (error) {
return res.status(400).json({ error: String(error) })
}
try {
let count: number = query.count || 25
let page: number = query.page || 1
let offset: number = (page - 1) * count
let matches: object[] = await produceService.search({
offset,
limit: count,
keyword: query.keyword,
cat_ids: query.cat,
})
return res.json({ matches })
} catch (error) {
return res.status(500).json({ error: String(error) })
}
})
class ProductService {
search(query: {
offset: number
limit: number
keyword: string
cat_ids?: number[]
}): Promise<Array<{ id: number; name: string }>> {
console.log('productService.search():', query)
throw new Error('mock implementation')
}
}
let produceService = new ProductService()