added functionality for user subscriptions

This commit is contained in:
Mikayla Dobson
2022-11-26 12:52:59 -06:00
parent 99c48d2a6e
commit 03ec2bf38c
18 changed files with 279 additions and 40 deletions

View File

@@ -1,6 +1,10 @@
import { ICollection } from "../schemas";
import { ICollection, IUser } from "../schemas";
import { User } from "./user";
import { appRoot } from "../appRoot";
import now from "../util/now";
import pool from "../db";
import fs from 'fs';
const UserInstance = new User();
export class Collection {
async getOne(id: string) {
try {
@@ -31,11 +35,11 @@ export class Collection {
try {
const statement = `
INSERT INTO recipin.collection
(name, active, ismaincollection, ownerid)
VALUES ($1, $2, $3, $4)
(name, active, ismaincollection, ownerid, datecreated, datemodified)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *;
`
const values = [name, active, ismaincollection, ownerid];
const values = [name, (active || true), (ismaincollection || false), ownerid, now, now];
const result = await pool.query(statement, values);
if (result.rows.length) return result.rows;
return null;
@@ -43,4 +47,92 @@ export class Collection {
throw new Error(e);
}
}
async getSubscriptions(userid: string) {
try {
const sql = fs.readFileSync(appRoot + '/db/sql/get/getsubscriptions.sql').toString();
console.log(sql);
const result = await pool.query(sql, [userid]);
if (result.rows.length) return result.rows;
return null;
} catch (e: any) {
throw new Error(e);
}
}
async postSubscription(collectionid: string, userid: string): Promise<{ ok: boolean, code: number, data: string | any[] }> {
try {
// ensure user exists
const user: IUser | null = await UserInstance.getOneByID(userid);
if (!user) {
return {
ok: false,
code: 404,
data: "User not found"
}
}
// ensure collection exists
const target: ICollection | null = await this.getOne(collectionid);
if (!target) {
return {
ok: false,
code: 404,
data: "Collection not found"
}
}
// ensure a user cannot subscribe to their own collection
if (target.ownerid == parseInt(userid)) {
return {
ok: false,
code: 403,
data: "User cannot subscribe to their own collection"
}
}
// ensure a duplicate subscription does not exist
const allSubscriptions = `
SELECT * FROM recipin.cmp_usersubscriptions
WHERE collectionid = $1;
`
const subscriptionResult = await pool.query(allSubscriptions, [collectionid]);
if (subscriptionResult.rows?.length) {
for (let row of subscriptionResult.rows) {
if (row.usermemberid == parseInt(userid)) {
return {
ok: false,
code: 403,
data: "This user is already subscribed"
}
}
}
}
// finally, execute insertion
const statement = `
INSERT INTO recipin.cmp_usersubscriptions
(collectionid, usermemberid)
VALUES ($1, $2)
RETURNING *;
`
const result = await pool.query(statement, [collectionid, userid]);
if (result.rows.length) {
return {
ok: true,
code: 201,
data: result.rows
}
}
return {
ok: false,
code: 400,
data: "Bad request. No data returned."
}
} catch (e: any) {
throw new Error(e);
}
}
}