Skip to content

Commit

Permalink
feat(qrshard): prevent if already exists (#394)
Browse files Browse the repository at this point in the history
  • Loading branch information
VictorWinberg authored Sep 16, 2022
1 parent fc1aedd commit 270dc4c
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 12 deletions.
1 change: 0 additions & 1 deletion client/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { EVENT_TYPE } from "@/constants";
import Snackbar from "node-snackbar";
import CustomSnackbar from "@/plugins/snackbar";
import EventBus from "@/plugins/event-bus";

Expand Down
11 changes: 5 additions & 6 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"node-cache": "^5.1.2",
"node-fetch": "2.6.7",
"nodemon": "2.0.19",
"passport": "0.6.0",
"passport": "0.5.3",
"passport-google-oauth": "2.0.0",
"pg": "8.7.3",
"snakecase-keys": "4.0.2",
Expand Down
27 changes: 23 additions & 4 deletions server/src/qrshard/qrshard-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,25 @@

const { keyValuePairs } = require("../utils");

module.exports = (db) => ({
module.exports = db => ({
create: async (userId, qrshard) => {
const valid = ["rating", "comment", "qrspot_id"];
const { keys, values, indices } = keyValuePairs(valid, qrshard);
await db.query("BEGIN TRANSACTION");

const { exists, err: existsErr } = await alreadyExists(db, userId, qrshard);
if (exists || existsErr) {
await db.query("ROLLBACK");
return { err: existsErr || "Already exists" };
}

const sql = `
INSERT INTO qrshards ( ${keys.concat("user_id")} )
INSERT INTO qrshards ( ${keys.concat("user_id")} )
VALUES (${indices.concat(userId)})
RETURNING *`;

const { rows, err } = await db.query(sql, values);
await db.query("COMMIT");
return { qrshard: rows[0], err };
},

Expand All @@ -39,7 +48,7 @@ module.exports = (db) => ({
return { qrshard: rows[0], err };
},

getAll: async (userId) => {
getAll: async userId => {
const sql = "SELECT * FROM qrshards WHERE user_id = $1";

const { rows, err } = await db.query(sql, [userId]);
Expand All @@ -56,5 +65,15 @@ module.exports = (db) => ({

const { rows, err } = await db.query(sql, [userId, qrcode]);
return { qrshard: rows[0], err };
},
}
});

const alreadyExists = async (db, userId, qrshard) => {
const sql = `
SELECT * FROM qrshards
WHERE user_id = $1 AND qrspot_id = $2
AND created_at::date = now()::date
`;
const { rows, err } = await db.query(sql, [userId, qrshard.qrspot_id]);
return { exists: (rows || []).length > 0, err };
};

0 comments on commit 270dc4c

Please sign in to comment.