-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
166 lines (141 loc) · 4.12 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const helmet = require("helmet");
const compression = require("compression");
const rateLimit = require("express-rate-limit");
const { pool } = require("./config");
const app = express();
app.use(compression());
app.use(helmet());
app.use(bodyParser.json({ limit: "1mb" }));
app.use(bodyParser.urlencoded({ extended: true, limit: "1mb" }));
app.use(cors());
const getJobs = (request, response) => {
let query = `SELECT * FROM jobs`;
if(request.query.search) {
const searchTerms = request.query.search.toLowerCase().trim().replace(/ /g, '|');
query = `SELECT * FROM jobs WHERE
LOWER(title) ~ '${searchTerms}'
OR LOWER(description) ~ '${searchTerms}'
OR LOWER(tags) ~ '${searchTerms}'
`;
}
pool.query(query, (error, results) => {
if (error) {
console.log("get jobs error => ", error);
throw error;
}
response.status(200).json(results.rows);
});
};
/**
* Add a single job to our DB
* @param {Object} request
* @param {Object} response
*/
const addJob = (request, response) => {
const {
source,
sourceID,
type,
sourceUrl,
creationDate,
company,
companyUrl,
companyLogoUrl,
title,
description,
tags,
category,
applyUrl,
} = request.body;
pool.query(
"INSERT INTO jobs (source, sourceID, type, sourceUrl, creationDate, company, companyUrl, companyLogoUrl, title, description, tags, category, applyUrl) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) ON CONFLICT (sourceID) DO NOTHING",
[
source,
sourceID,
type,
sourceUrl,
creationDate,
company,
companyUrl,
companyLogoUrl,
title,
description,
tags,
category,
applyUrl,
],
(queryError, queryResponse) => {
if (queryError) {
throw queryError;
}
console.info(
`=> ${
queryResponse.rowCount
} jobs added out of 1 possible on ${new Date()
.toJSON()
.slice(0, 10)} at ${new Date().toJSON().slice(11, 19)}`
);
response.status(201).json({ status: "success", message: "Job added." });
}
);
};
/**
* Add multiple jobs to our DB with a single INSERT
* @param {Object} request
* @param {Object} response
*/
const addJobs = (request, response) => {
// We need to transponse the array of objects into a bidimensional array
// In order to do a multiple row insert
const dataTransposed = request.body.reduce(
(acc, job) => {
Object.keys(job).forEach((key, index) => acc[index].push(job[key]));
return [...acc];
},
Object.keys(request.body[0]).map((item) => new Array())
);
// Define insert query using unnest
const insertQuery = `INSERT INTO
jobs (source, sourceID, type, sourceUrl, creationDate, company, companyUrl,
companyLogoUrl, title, description, tags, category, applyUrl)
SELECT * FROM UNNEST ($1::varchar[], $2::varchar[], $3::varchar[], $4::text[], $5::varchar[],
$6::varchar[], $7::text[], $8::text[], $9::varchar[], $10::text[],$11::text[], $12::varchar[],$13::text[])
ON CONFLICT (sourceID) DO NOTHING`;
// Run insert query
pool.query(insertQuery, dataTransposed, (queryError, queryResponse) => {
if (queryError) {
throw queryError;
}
console.info(
`=> ${queryResponse.rowCount} jobs added out of ${
request.body.length
} possible on ${new Date()
.toJSON()
.slice(0, 10)} at ${new Date().toJSON().slice(11, 19)}`
);
response.status(201).json({
status: "success",
message: `${request.body.length} jobs added`,
});
});
};
const mainLimiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 5, // 5 requests,
});
app.use(mainLimiter);
const postLimiter = rateLimit({
windowMs: 1 * 60 * 1000,
max: 1,
});
app.route("/jobs").get(getJobs).post(addJobs);
app.route("/job").post(postLimiter, addJob);
// Start server
app.listen(process.env.PORT || 3002, () => {
console.log(`Server listening...\n`);
});
// Export our app for testing purposes
module.exports = { app };