Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"semi": true,
"singleQuote": false,
"trailingComma": "all",
"tabWidth": 2,
"printWidth": 80,
"endOfLine": "lf"
}
3 changes: 3 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]
}
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"prettier.requireConfig": true
}
3 changes: 3 additions & 0 deletions backend/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dist
data
package-lock.json
17 changes: 17 additions & 0 deletions backend/package-lock.json

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

5 changes: 4 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"build": "tsc",
"start": "node dist/index.js",
"import": "tsx src/scripts/import.ts",
"seed": "tsx src/scripts/seed.ts"
"seed": "tsx src/scripts/seed.ts",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"keywords": [],
"author": "",
Expand All @@ -22,6 +24,7 @@
"devDependencies": {
"@types/node": "^24.19.0",
"@types/pg": "^8.23.1",
"prettier": "3.9.10",
"tsx": "^4.23.15",
"typescript": "~6.0.2"
}
Expand Down
9 changes: 5 additions & 4 deletions backend/src/context.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
import type { IncomingMessage } from 'node:http';
import type { IncomingMessage } from "node:http";

export interface Context {
ownerId: string;
}

// Godtar bare id-er som ser ut som en uuid fra crypto.randomUUID()
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export const createContext = async ({
req,
}: {
req: IncomingMessage;
}): Promise<Context> => {
const header = req.headers['x-user-id'];
const header = req.headers["x-user-id"];
const userId = Array.isArray(header) ? header[0] : header;

// Uten gyldig header (f.eks. i Apollo Sandbox) brukes 'anonymous', som i dag.
// Senere kan innlogget bruker hentes her i stedet.
return {
ownerId: userId && UUID_PATTERN.test(userId) ? userId : 'anonymous',
ownerId: userId && UUID_PATTERN.test(userId) ? userId : "anonymous",
};
};
6 changes: 3 additions & 3 deletions backend/src/db.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import 'dotenv/config';
import pg from 'pg';
import "dotenv/config";
import pg from "pg";

const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error('DATABASE_URL mangler i backend/.env (se .env.example)');
throw new Error("DATABASE_URL mangler i backend/.env (se .env.example)");
}

// Én felles tilkoblingspool for hele backenden.
Expand Down
18 changes: 11 additions & 7 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import 'dotenv/config';
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { typeDefs } from './schema.js';
import { resolvers } from './resolvers/resolvers.js';
import { createContext, type Context } from './context.js';
import "dotenv/config";
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import { typeDefs } from "./schema.js";
import { resolvers } from "./resolvers/resolvers.js";
import { createContext, type Context } from "./context.js";

const server = new ApolloServer<Context>({ typeDefs, resolvers, introspection: true });
const server = new ApolloServer<Context>({
typeDefs,
resolvers,
introspection: true,
});

// Port 3001 er kravet i oppgaven, men kan overstyres i .env
const port = Number(process.env.PORT ?? 3001);
Expand Down
107 changes: 47 additions & 60 deletions backend/src/resolvers/products.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pool } from '../db.js';
import { pool } from "../db.js";

export const categories = async () => {
const result = await pool.query(`
Expand All @@ -14,8 +14,8 @@ export const categories = async () => {
};

export const product = async (_parent: unknown, args: { ean: string }) => {
const result = await pool.query(
`
const result = await pool.query(
`
SELECT
ean,
name,
Expand All @@ -28,10 +28,10 @@ export const product = async (_parent: unknown, args: { ean: string }) => {
FROM products
WHERE ean = $1
`,
[args.ean],
);
[args.ean],
);

return result.rows[0] ?? null;
return result.rows[0] ?? null;
};

export const products = async (
Expand All @@ -49,20 +49,11 @@ export const products = async (
const categories = args.categories ?? [];
const storeCodes = args.storeCodes ?? [];

const allowedSorts = [
"relevance",
"price_asc",
"price_desc",
];
const allowedSorts = ["relevance", "price_asc", "price_desc"];

const sort = allowedSorts.includes(args.sort ?? "")
? args.sort
: "relevance";
const sort = allowedSorts.includes(args.sort ?? "") ? args.sort : "relevance";

const limit = Math.min(
Math.max(args.limit ?? 20, 1),
100,
);
const limit = Math.min(Math.max(args.limit ?? 20, 1), 100);

const offset = Math.max(args.offset ?? 0, 0);

Expand Down Expand Up @@ -150,14 +141,7 @@ export const products = async (
LIMIT $4
OFFSET $5
`,
[
search,
categories,
storeCodes,
limit,
offset,
sort,
],
[search, categories, storeCodes, limit, offset, sort],
);

return result.rows;
Expand Down Expand Up @@ -218,7 +202,9 @@ export const productsCount = async (
return result.rows[0].count;
};

export const productCategory = async (product: { categoryId?: number | null }) => {
export const productCategory = async (product: {
categoryId?: number | null;
}) => {
if (!product.categoryId) {
return null;
}
Expand Down Expand Up @@ -261,37 +247,38 @@ export const productPrices = async (product: { ean: string }) => {
return result.rows;
};

export const nutrition = (
product: {
nutrition?: {
code: string;
display_name: string;
amount: number;
unit: string;
}[] | null;
}) => {
return (product.nutrition ?? []).map((item) => ({
code: item.code,
displayName: item.display_name,
amount: item.amount,
unit: item.unit,
}));
};
export const nutrition = (product: {
nutrition?:
| {
code: string;
display_name: string;
amount: number;
unit: string;
}[]
| null;
}) => {
return (product.nutrition ?? []).map((item) => ({
code: item.code,
displayName: item.display_name,
amount: item.amount,
unit: item.unit,
}));
};

export const allergens =(
product: {
allergens?: {
code: string;
display_name: string;
contains: string;
}[] | null;
}) => {
return (product.allergens ?? [])
.filter((item) => item.contains !== "NO")
.map((item) => ({
code: item.code,
displayName: item.display_name,
contains: item.contains,
}));
};
export const allergens = (product: {
allergens?:
| {
code: string;
display_name: string;
contains: string;
}[]
| null;
}) => {
return (product.allergens ?? [])
.filter((item) => item.contains !== "NO")
.map((item) => ({
code: item.code,
displayName: item.display_name,
contains: item.contains,
}));
};
10 changes: 4 additions & 6 deletions backend/src/resolvers/resolvers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
categoryFilterCounts,
storeFilterCounts,
} from './filters.js';
import { categoryFilterCounts, storeFilterCounts } from "./filters.js";
import {
allergens,
categories,
Expand All @@ -11,7 +8,7 @@ import {
productPrices,
products,
productsCount,
} from './products.js';
} from "./products.js";
import {
addItemToList,
completeShoppingList,
Expand All @@ -28,6 +25,7 @@ import {
shoppingListItems,
updateItemNote,
updateItemQuantity,

} from './shoppingLists.js';
import { stores } from './stores.js';

Expand Down Expand Up @@ -62,7 +60,7 @@ export const resolvers = {
category: productCategory,
prices: productPrices,
nutrition,
allergens
allergens,
},

ShoppingList: {
Expand Down
Loading