Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions backend/migrations/1794333349979_create-review-table.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- Up Migration

-- Student reviews. A user is an anonymous ID stored in the browser until we have login.
CREATE TABLE review (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
wine_id integer NOT NULL REFERENCES wine (id) ON DELETE CASCADE,
user_id uuid NOT NULL,
rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 6), -- die roll
comment text CHECK (char_length(comment) <= 500),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (wine_id, user_id) -- one review per user per wine
);

-- For "Nylig dømt": the newest reviews first.
CREATE INDEX review_created_at ON review (created_at DESC);

-- Down Migration

DROP TABLE review;
116 changes: 115 additions & 1 deletion backend/src/resolvers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
// Resolvers: the functions that fetch data for each field in the schema.
import { GraphQLError } from 'graphql';
import { pool } from './db';
import {
authorName,
validateReviewInput,
validateUserId,
validateWineId,
type ReviewInput,
} from './review-input';
import {
buildFilterOptionsQueries,
buildWinesQuery,
Expand All @@ -8,6 +16,9 @@ import {
type WinesArgs,
} from './wine-query';

// The most reviews one query can ask for.
const MAX_REVIEWS = 50;

// A row from the wine table, as returned by pg.
interface WineRow {
id: number;
Expand All @@ -29,6 +40,17 @@ interface WineRow {
community_count: number;
}

// A row from the review table.
interface ReviewRow {
id: number;
wine_id: number;
user_id: string;
rating: number;
comment: string | null;
created_at: Date;
updated_at: Date;
}

// Converts database names (snake_case) to GraphQL names (camelCase).
function toWine(row: WineRow) {
return {
Expand All @@ -52,6 +74,24 @@ function toWine(row: WineRow) {
};
}

// The user ID is left out on purpose, so it is never sent to other users.
function toReview(row: ReviewRow) {
return {
id: String(row.id),
wineId: row.wine_id,
rating: row.rating,
comment: row.comment,
author: authorName(row.user_id),
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString(),
};
}

/** Keeps "first" between 1 and MAX_REVIEWS, whatever the frontend sends. */
function limitReviews(first: number | null | undefined, fallback: number): number {
return Math.min(Math.max(first ?? fallback, 1), MAX_REVIEWS);
}

async function filterOptions(
args: FilterArgs,
group: keyof ReturnType<typeof buildFilterOptionsQueries>,
Expand Down Expand Up @@ -88,14 +128,62 @@ export const resolvers = {
async wine(_parent: unknown, args: { id: string }) {
const id = Number(args.id);
if (!Number.isInteger(id)) return null;
const result = await pool.query<WineRow>('SELECT * FROM wine WHERE id = $1', [id]);
const result = await pool.query<WineRow>('SELECT * FROM wine WHERE id = $1', [id]);
return result.rows[0] ? toWine(result.rows[0]) : null;
},

// The counts are in the fields below, so a query only pays for the groups it asks for.
filterOptions(_parent: unknown, args: FilterArgs) {
return args;
},

async recentReviews(_parent: unknown, args: { first?: number | null }) {
const result = await pool.query<ReviewRow>(
'SELECT * FROM review ORDER BY created_at DESC, id DESC LIMIT $1',
[limitReviews(args.first, 5)],
);
return result.rows.map(toReview);
},

async myReview(_parent: unknown, args: { wineId: string; userId: string }) {
const result = await pool.query<ReviewRow>(
'SELECT * FROM review WHERE wine_id = $1 AND user_id = $2',
[validateWineId(args.wineId), validateUserId(args.userId)],
);
return result.rows[0] ? toReview(result.rows[0]) : null;
},
},

Mutation: {
async saveReview(_parent: unknown, args: { input: ReviewInput }) {
const review = validateReviewInput(args.input);
try {
// Adds the review, or updates the old one if this user has already reviewed the wine.
const result = await pool.query<ReviewRow>(
`INSERT INTO review (wine_id, user_id, rating, comment)
VALUES ($1, $2, $3, $4)
ON CONFLICT (wine_id, user_id)
DO UPDATE SET rating = EXCLUDED.rating, comment = EXCLUDED.comment, updated_at = now()
RETURNING *`,
[review.wineId, review.userId, review.rating, review.comment],
);
return toReview(result.rows[0]);
} catch (error) {
// 23503 = foreign key violation: the wine does not exist.
if ((error as { code?: string }).code === '23503') {
throw new GraphQLError('Wine not found.', { extensions: { code: 'BAD_USER_INPUT' } });
}
throw error;
}
},

async deleteReview(_parent: unknown, args: { wineId: string; userId: string }) {
const result = await pool.query(
'DELETE FROM review WHERE wine_id = $1 AND user_id = $2',
[validateWineId(args.wineId), validateUserId(args.userId)],
);
return (result.rowCount ?? 0) > 0;
},
},

FilterOptions: {
Expand All @@ -104,4 +192,30 @@ export const resolvers = {
grapes: (args: FilterArgs) => filterOptions(args, 'grapes'),
harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'),
},

// Fields on Wine that are not columns in the wine table. They only run when the frontend asks for them.
Wine: {
async studentRating(wine: { id: string }) {
const result = await pool.query<{ average: number | null; count: number }>(
'SELECT AVG(rating)::float AS average, COUNT(*)::int AS count FROM review WHERE wine_id = $1',
[Number(wine.id)],
);
return result.rows[0];
},

async reviews(wine: { id: string }, args: { first?: number | null }) {
const result = await pool.query<ReviewRow>(
'SELECT * FROM review WHERE wine_id = $1 ORDER BY updated_at DESC, id DESC LIMIT $2',
[Number(wine.id), limitReviews(args.first, 10)],
);
return result.rows.map(toReview);
},
},

Review: {
async wine(review: { wineId: number }) {
const result = await pool.query<WineRow>('SELECT * FROM wine WHERE id = $1', [review.wineId]);
return toWine(result.rows[0]);
},
},
};
68 changes: 68 additions & 0 deletions backend/src/review-input.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest';
import { authorName, MAX_COMMENT_LENGTH, validateReviewInput } from './review-input';

const USER_ID = '3f2a9c1e-8b4d-4e2a-9f1c-2b7d6e5a4c3b';

describe('validateReviewInput', () => {
it('accepts a valid review and converts the wine ID to a number', () => {
const review = validateReviewInput({ wineId: '100062', userId: USER_ID, rating: 5, comment: 'Godt!' });
expect(review).toEqual({ wineId: 100062, userId: USER_ID, rating: 5, comment: 'Godt!' });
});

it('accepts every side of the die', () => {
for (const rating of [1, 2, 3, 4, 5, 6]) {
expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating }).rating).toBe(rating);
}
});

it('rejects ratings outside the die and half values', () => {
for (const rating of [0, 7, -1, 3.5]) {
expect(() => validateReviewInput({ wineId: '1', userId: USER_ID, rating })).toThrow('rating');
}
});

it('stores a blank comment as no comment', () => {
expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4, comment: ' ' }).comment).toBeNull();
expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4 }).comment).toBeNull();
});

it('trims the comment', () => {
expect(validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4, comment: ' Fin ' }).comment).toBe('Fin');
});

it('rejects a comment that is too long', () => {
const comment = 'a'.repeat(MAX_COMMENT_LENGTH + 1);
expect(() => validateReviewInput({ wineId: '1', userId: USER_ID, rating: 4, comment })).toThrow('comment');
});

it('rejects invalid wine IDs', () => {
for (const wineId of ['abc', '-1', '0', '1.5']) {
expect(() => validateReviewInput({ wineId, userId: USER_ID, rating: 4 })).toThrow('wine ID');
}
});

it('rejects a user ID that is not a UUID', () => {
expect(() => validateReviewInput({ wineId: '1', userId: 'student-1', rating: 4 })).toThrow('user ID');
});

it('gives a BAD_USER_INPUT error so the frontend can show the message', () => {
try {
validateReviewInput({ wineId: '1', userId: USER_ID, rating: 9 });
} catch (error) {
expect((error as { extensions: { code: string } }).extensions.code).toBe('BAD_USER_INPUT');
}
expect.assertions(1);
});
});

describe('authorName', () => {
it('gives the same name for the same user', () => {
expect(authorName(USER_ID)).toBe(authorName(USER_ID));
});

it('looks like "Student #" and four digits, and never shows the ID', () => {
const name = authorName(USER_ID);
expect(name).toMatch(/^Student #\d{4}$/);
expect(name).not.toContain(USER_ID.slice(0, 8));
});
});
63 changes: 63 additions & 0 deletions backend/src/review-input.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Checks and cleans the input to saveReview. Kept separate from the database so it is easy to test.
import { GraphQLError } from 'graphql';

export const MIN_RATING = 1;
export const MAX_RATING = 6; // Die roll. Change together with the CHECK in the review migration.
export const MAX_COMMENT_LENGTH = 500;

export interface ReviewInput {
wineId: string;
userId: string;
rating: number;
comment?: string | null;
}

export interface ValidReview {
wineId: number;
userId: string;
rating: number;
comment: string | null;
}

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

function badInput(message: string): GraphQLError {
return new GraphQLError(message, { extensions: { code: 'BAD_USER_INPUT' } });
}

export function validateWineId(value: string): number {
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) throw badInput('Invalid wine ID.');
return id;
}

export function validateUserId(value: string): string {
if (!UUID.test(value)) throw badInput('Invalid user ID.');
return value.toLowerCase();
}

export function validateReviewInput(input: ReviewInput): ValidReview {
const { rating } = input;
if (!Number.isInteger(rating) || rating < MIN_RATING || rating > MAX_RATING) {
throw badInput(`The rating must be a whole number from ${MIN_RATING} to ${MAX_RATING}.`);
}

// An empty or blank comment is stored as no comment.
const comment = input.comment?.trim() || null;
if (comment && comment.length > MAX_COMMENT_LENGTH) {
throw badInput(`The comment can be at most ${MAX_COMMENT_LENGTH} characters.`);
}

return {
wineId: validateWineId(input.wineId),
userId: validateUserId(input.userId),
rating,
comment,
};
}

/** A stable display name made from the anonymous ID, e.g. "Student #4821". The ID itself is never shown. */
export function authorName(userId: string): string {
const number = (parseInt(userId.replace(/-/g, '').slice(0, 8), 16) % 9000) + 1000;
return `Student #${number}`;
}
44 changes: 44 additions & 0 deletions backend/src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export const typeDefs = `#graphql
"Average X-Wines rating (1-5), or null if nobody has rated the wine."
communityRating: Float
communityRatingCount: Int!
"Average die roll from students on Kork & Krone."
studentRating: StudentRating!
"The newest student reviews of this wine."
reviews(first: Int = 10): [Review!]!
}

type WineEdge {
Expand Down Expand Up @@ -74,6 +78,32 @@ export const typeDefs = `#graphql
harmonize: [FilterOption!]!
}

type StudentRating {
"Average die roll (1-6), or null if no student has reviewed the wine."
average: Float
count: Int!
}

type Review {
id: ID!
"Die roll from 1 to 6."
rating: Int!
comment: String
"Display name such as 'Student #4821'. The user ID is never shown."
author: String!
createdAt: String!
updatedAt: String!
wine: Wine!
}

input ReviewInput {
wineId: ID!
"The anonymous ID stored in the browser."
userId: ID!
rating: Int!
comment: String
}

type Query {
"Search, filter and sort wines. Use pageInfo.endCursor as 'after' to load the next page."
wines(
Expand All @@ -88,5 +118,19 @@ export const typeDefs = `#graphql

"Values for the filter panel. The counts follow the search and the filters in the other groups."
filterOptions(search: String, filter: WineFilter): FilterOptions!

"The newest student reviews across all wines."
recentReviews(first: Int = 5): [Review!]!

"The user's own review of a wine, so the form can show it again."
myReview(wineId: ID!, userId: ID!): Review
}

type Mutation {
"Adds a review, or updates the user's earlier review of the same wine."
saveReview(input: ReviewInput!): Review!

"Deletes the user's review of a wine. Returns false if there was none."
deleteReview(wineId: ID!, userId: ID!): Boolean!
}
`;
Loading