-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
105 lines (84 loc) · 2.46 KB
/
index.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
const express = require('express')
const server = express()
const middleware = require("https");
const _ = require('lodash')
const keyApi = "0oaTF6zE2p4GTDrPw99o7n0J9sPWtEgr";
// supose to be in .env file
const hostMiddlewareConfig = {
host: "api.nytimes.com",
port: 443,
method: "GET",
};
// function to setApi and get parameter to search
let putApiToOption = (apiKey, searchKeyWord, middlewareEndPoint, method) => {
let options = {
hostname: hostMiddlewareConfig.host,
port: hostMiddlewareConfig.port,
path: `${middlewareEndPoint}` + `${searchKeyWord}+&api-key=${keyApi}`,
method: method,
};
// console.log(options.path)
return options
}
// api url to search articles
https: server.get(
"/search_article/:searchContent/:isSort",
(req, res, next) => {
let reqToMiddleware = middleware.get(
putApiToOption(
keyApi,
`q=${req.params.searchContent}`,
`/svc/search/v2/articlesearch.json?`, 'GET'
),
(resMiddleWare) => {
console.log(`statusCode: ${resMiddleWare.statusCode}`);
let data = "";
resMiddleWare.on("data", (chunk) => {
data += chunk;
console.log(chunk instanceof Buffer);
});
resMiddleWare.on("close", () => {
// get the part data only
let result = JSON.parse(data).response;
// for sorting if paramisSort isSort fill by "ascending"
result =
req.params.isSort === "ascending"
? _.sortBy(result.docs, function (item) {
return item.pub_date;
})
: result;
res.json({ articles: result });
});
}
);
}
);
// api for get books
https: server.get(
"/search_books/:searchContent/:isSort",
(req, res, next) => {
let reqToMiddleware = middleware.get(
putApiToOption(
keyApi,
``,
`/svc/books/v3/lists/current/hardcover-fiction.json?`, 'GET'
),
(resMiddleWare) => {
console.log(`statusCode: ${resMiddleWare.statusCode}`);
let data = "";
resMiddleWare.on("data", (chunk) => {
data += chunk;
console.log(chunk instanceof Buffer);
});
resMiddleWare.on("close", () => {
// get the part data only
let result = JSON.parse(data).results;
res.json({ books: result.books });
});
}
);
}
);
server.listen(3000, function () {
console.log('server is started')
})