forked from GetStream/stream-react-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearches.js
More file actions
71 lines (62 loc) · 1.81 KB
/
Copy pathsearches.js
File metadata and controls
71 lines (62 loc) · 1.81 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
'use strict';
/**
* Get all searches performed by a user (aka search history)
* URL: /searches
* Method: GET
* Auth Required: Yes
* @param {string} user_id This required param specifies the user id to filter by
* @returns {object} Returns a 200 status code with an array of search objects
*/
server.get('/searches', function(req, res, next) {
// extract query params
var params = req.params || {};
// build sql query
var sql = `
SELECT
search,
created_at
FROM searches
WHERE searches.user_id = ?
GROUP BY searches.search
ORDER BY created_at DESC
LIMIT 10
`;
// execute query
db.query(sql, [params.user_id], function(err, results) {
// catch all errors
if (err) {
// use global logger to log to console
log.error(err);
// return error message to client
return next(new restify.InternalError(err.message));
}
// send response to client
res.send(200, results);
return next();
});
});
/**
* Create a search record for history lookup
* URL: /searches
* Method: POST
* Auth Required: Yes
* @param {string} user_id This required param specifies the user id to associate search with
* @param {string} search This required param specifies the search value
* @returns {object} Returns a 200 status code with an array of search objects
*/
server.post('/searches', function(req, res, next) {
// extract params from body
var data = req.body || {};
// execute query using data from body
db.query('INSERT INTO searches SET ?', data, function(err, result) {
if (err) {
log.error(err);
return next(new restify.InternalError(err.message));
}
// user object.assign to inject new record id
result = Object.assign({ id: result.insertId }, data);
// send response to client
res.send(201, result);
return next();
});
});