-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy-search.js
91 lines (78 loc) · 2.39 KB
/
proxy-search.js
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
require('dotenv').config();
const fastify = require('fastify')({logger: true});
const PORT = 5000;
// add CORS SUPPORT
fastify.register(require('@fastify/cors'), {
// add your own domain for security
origin: '*',
});
// Fastify route for POST /search
fastify.post('/search', async (request, reply) => {
try {
const raw = JSON.stringify({
"user_app_id": {
"user_id": process.env.CLARIFAI_USER_ID,
"app_id": process.env.CLARIFAI_APP_ID
},
"pagination": {
"per_page": 10
},
"searches": [
{
"query": {
"ranks": [
{
"annotation": {
"data": {
"text": {
"raw": request.body.text
}
}
}
}
]
}
}
]
});
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Key ' + process.env.CLARIFAI_PAT
},
body: raw
};
out = await fetch(`https://api.clarifai.com/v2/inputs/searches?per_page=10`, requestOptions)
//convert readable stream to string
out = await out.json();
console.dir(out, {depth: null});
// cleanup results
results = out.hits.map(hit => {
return {
score: hit.score,
title: hit.input.data.metadata.title,
url: hit.input.data.metadata.url,
};
});
reply.send(results);
} catch (error) {
// Handle errors
fastify.log.error(error);
reply.status(500).send({
error: 'Failed to fetch results from Clarifai',
details: error.message,
});
}
});
// Start the Fastify server
const start = async () => {
try {
await fastify.listen({port: PORT});
fastify.log.info(`Server is running on http://localhost:${PORT}`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();