diff --git a/db/50-views.sql b/db/50-views.sql index e138874..39bac62 100644 --- a/db/50-views.sql +++ b/db/50-views.sql @@ -1,2 +1,5 @@ CREATE VIEW requests_vw AS - SELECT * FROM requests WHERE state = 'Requested' ORDER BY score DESC; + SELECT * FROM requests WHERE state = 'Requested' ORDER BY score DESC, id DESC; + +CREATE VIEW requests_all_vw AS + SELECT * FROM requests ORDER BY id DESC; diff --git a/src/app.ts b/src/app.ts index 77eb006..947ad92 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,4 +1,5 @@ import * as config from "./config"; +import * as requests from "./requests"; import express from "express"; import db from "./db"; @@ -6,7 +7,15 @@ const app = express(); app.use(express.static('public')); app.use(express.json()); -app.get("/test", (request, response) => response.send("Test")) +app.get("/api/getRequests", async (request, response) => { + var requestCount = ( request.query.count ? parseInt(request.query.count as string, 10) : 5 ); + requests.getRequests(requestCount,response); +}); + +app.get("/api/getAllRequests", async (request, response) => { + var requestCount = ( request.query.count ? parseInt(request.query.count as string, 10) : 5 ); + requests.getAllRequests(requestCount,response); +}); const server = app.listen(config.port, () => { console.log(`Listening on port ${config.port}`); diff --git a/src/requests.ts b/src/requests.ts new file mode 100644 index 0000000..ab4c784 --- /dev/null +++ b/src/requests.ts @@ -0,0 +1,47 @@ +import express from "express"; +import pg from "pg"; +import db from "./db"; + +// getRequests +const getRequestsQuery = { + name: "getRequests", + text: "SELECT * FROM requests_vw LIMIT $1" +} + +export async function getRequests(count: number, response: express.Response) { + var query = Object.assign(getRequestsQuery, { values: [count] }); + db.query(query) + .then((result: pg.QueryResult) => response.send(result.rows)) + .catch((e: any) => console.error(e.stack)); +}; + +// getAllRequests +const getAllRequestsQuery = { + name: "getAllRequests", + text: "SELECT * FROM requests_all_vw LIMIT $1" +} + +export async function getAllRequests(count: number, response: express.Response) { + var query = Object.assign(getAllRequestsQuery, { values: [count] }); + db.query(query) + .then((result: pg.QueryResult) => response.send(result.rows)) + .catch((e: any) => console.error(e.stack)); +}; + +// addRequest +//const checkRequestExistsQuery = { +// name: "checkRequestExists", +// text: "SELECT COUNT(*) FROM requests WHERE url = $1" +//} +// +//const addRequestQuery = { +// name: "addRequest", +// text: "INSERT INTO requests (url,requester) VALUES ($1,$2)" +//} +// +//export async function addRequest(url: string, response: express.Response) { +// var query = Object.assign(getAllRequestsQuery, { values: [count] }); +// db.query(query) +// .then((result: pg.QueryResult) => response.send(result.rows)) +// .catch((e: any) => console.error(e.stack)); +//};