-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathself-deployed-api.ts
60 lines (45 loc) · 1.5 KB
/
self-deployed-api.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
import express from 'express'
import {Filter} from 'mongodb'
import cors from 'cors'
import {mongoClient, MONGODB_COLLECTION} from './util'
import {User} from './util'
const app = express()
app.use(cors({credentials: true, origin: 'http://localhost:4000'}))
app.get('/search', async (req, res) => {
const searchQuery = req.query.query as string
const country = req.query.country as string
if (!searchQuery || searchQuery.length < 2) {
res.json([])
return
}
const db = mongoClient.db('tutorial')
const collection = db.collection<User>(MONGODB_COLLECTION)
const filter: Filter<User> = {
$text: {$search: searchQuery, $caseSensitive: false, $diacriticSensitive: false},
}
if (country) filter.country = country
const result = await collection
.find(filter)
.project({score: {$meta: 'textScore'}, _id: 0})
.sort({score: {$meta: 'textScore'}})
.limit(10)
const array = await result.toArray()
res.json(array)
})
async function main() {
try {
await mongoClient.connect()
const db = mongoClient.db('tutorial')
const collection = db.collection<User>(MONGODB_COLLECTION)
// Text index for searching fullName and email
await collection.createIndexes([{name: 'fullName_email_text', key: {fullName: 'text', email: 'text'}}])
app.listen(3000, () => console.log('http://localhost:3000/search?query=gilbert'))
} catch (err) {
console.log(err)
}
process.on('SIGTERM', async () => {
await mongoClient.close()
process.exit(0)
})
}
main()