Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backend endpoints #14

Merged
merged 17 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from 13 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
44 changes: 12 additions & 32 deletions backend/eslint.config.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,14 @@
import js from '@eslint/js'
import jest from 'eslint-plugin-jest'
import globals from 'globals'
import globals from "globals";
import pluginJs from "@eslint/js";

/** @type {import('eslint').Linter.Config[]} */
export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,ts}'],
languageOptions: {
ecmaVersion: 'latest',
globals: globals.node,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
rules: {
...js.configs.recommended.rules,
},
},
{
files: ['**/__tests__/**/*.test.{js,ts}'],
plugins: {
jest,
},
languageOptions: {
globals: jest.environments.globals.globals
},
rules: {
...jest.configs.recommended.rules,
}
}
]
{ languageOptions: { globals: { ...globals.node, ...globals.jest } } },
pluginJs.configs.recommended,
{
rules: {
camelcase: ["warn", { properties: "never", ignoreDestructuring: false }],
"max-len": ["warn", { code: 140 }],
},
},
];
7 changes: 3 additions & 4 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import cors from "cors";
import dotenv from "dotenv";
import express from "express";
import authRoutes from "./src/routes/authRoutes.js";
import logRoutes from "./src/routes/logRoutes.js";
import authRoutes from "./src/routes/auth-route.js";
import logRoutes from "./src/routes/logbooks-route.js";

dotenv.config();

Expand All @@ -15,9 +15,8 @@ const PORT = process.env.PORT || 8080;
app.use(cors(corsOptions));
app.use(express.json());

//Routes
app.use('/api/auth', authRoutes);
app.use('/api/log', logRoutes);
app.use('/api/logbooks', logRoutes);

app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
Expand Down
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"build": "babel index.js -d dist",
"dev": "nodemon server",
"lint": "eslint .",
"lint": "eslint",
"start": "node index.js",
"test": "jest"
},
Expand Down
3 changes: 0 additions & 3 deletions backend/src/middlewares/__tests__/auth.test.js

This file was deleted.

5 changes: 1 addition & 4 deletions backend/src/middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,12 @@ const auth = async (req, res, next) => {
})
req.supabase = supabase;
} else {
console.error("No token: Authentication Denied");
return res.status(401).json({ message: "No token: Authentication Denied" });
}
next();
} catch (err) {
console.error("Invalid token, authentication denied:", err.message);
return res.status(400).json({ message: `Invalid token, authentication denied: ${err.message}`});
}
};

export default auth;

export default auth;
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import auth from "../middlewares/auth.js";

const router = express.Router();

//auth test
router.post("/check", auth, async (req, res) => {
res.json({ message: "Auth Check Ok"});
})
Expand Down
17 changes: 0 additions & 17 deletions backend/src/routes/logRoutes.js

This file was deleted.

61 changes: 61 additions & 0 deletions backend/src/routes/logbooks-route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import express from "express";
import auth from "../middlewares/auth.js";
import { createLogbook, getUserLogbooks, getLogbook, createLog, getLogbookLogs, getLog } from "../services/logbooks-service.js";

const router = express.Router();

router.post("", auth, async (req, res) => {
const logbook = await createLogbook(req);
if (logbook.error) {
res.status(500).json({ error: logbook.error });
} else {
res.status(201).json({ data: logbook });
}
});

router.get("", auth, async (req, res) => {
const userLogbooks = await getUserLogbooks(req);
if (userLogbooks.error) {
res.status(500).json({ error: userLogbooks.error });
} else {
res.status(200).json({ data: userLogbooks });
}
});

router.get("/:logbookID", auth, async (req, res) => {
const logbook = await getLogbook(req);
if (logbook.error) {
res.status(500).json({ error: logbook.error });
} else {
res.status(200).json({ data: logbook });
}
});

router.post("/:logbookID/logs", auth, async (req, res) => {
const log = await createLog(req);
if (log.error) {
res.status(500).json({ error: log.error });
} else {
res.status(201).json({ data: log });
}
});

router.get("/:logbookID/logs", auth, async (req, res) => {
const logbookLogs = await getLogbookLogs(req);
if (logbookLogs.error) {
res.status(500).json({ error: logbookLogs.error });
} else {
res.status(200).json({ data: logbookLogs });
}
});

router.get("/:logbookID/logs/:logID", auth, async (req, res) => {
const log = await getLog(req);
if (log.error) {
res.status(500).json({ error: log.error });
} else {
res.status(200).json({ data: log });
}
});

export default router;
3 changes: 3 additions & 0 deletions backend/src/routes/test/auth-route.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
test("empty test", () => {
expect(true).toBe(true);
});
3 changes: 3 additions & 0 deletions backend/src/routes/test/logbooks-route.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
test("empty test", () => {
expect(true).toBe(true);
});
76 changes: 0 additions & 76 deletions backend/src/services/cardiacSurgeryAdultService.js

This file was deleted.

58 changes: 58 additions & 0 deletions backend/src/services/logbooks-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import getLogbookType from "../utils/get-logbook-type.js";
import getTable from "../utils/get-table.js";
import insertTable from "../utils/insert-table.js";
import parseUserID from "../utils/parse-user-id.js";

export async function createLogbook(req) {
const supabase = req.supabase;
const body = req.body
return insertTable(supabase, "logbooks", body);
}

export async function getUserLogbooks(req) {
const supabase = req.supabase;
const token = req.header("Authorization")?.split(" ")[1];
const userID = parseUserID(token);
return getTable(supabase, "logbooks", "user_id", userID, "collection");
}

export async function getLogbook(req) {
parkrafael marked this conversation as resolved.
Show resolved Hide resolved
const supabase = req.supabase;
const { logbookID } = req.params;
return getTable(supabase, "logbooks", "id", logbookID, "resource");
}

export async function createLog(req) {
try {
const supabase = req.supabase;
const { logbookID } = req.params;
let body = req.body
body['logbook_id'] = logbookID
const logbookType = await getLogbookType(logbookID, supabase);
if (body['type'] !== logbookType) {
throw new Error(`log type '${body['type']}' does not match logbook type '${logbookType}'`);
}
switch (body['type']) {
case "adult_cardiac_logs":
return insertTable(supabase, "adult_cardiac_logs", body)
default:
throw new Error(`log and logbook type '${body['type']}' are invalid`);
}
} catch (error) {
return { error: error.message };
}
}

export async function getLogbookLogs(req) {
parkrafael marked this conversation as resolved.
Show resolved Hide resolved
const supabase = req.supabase;
const { logbookID } = req.params;
const logbookType = await getLogbookType(logbookID, supabase);
return getTable(supabase, logbookType, "logbook_id", logbookID, "collection");
}

export async function getLog(req) {
const supabase = req.supabase;
const { logbookID, logID } = req.params;
const logbookType = await getLogbookType(logbookID, supabase);
return getTable(supabase, logbookType, "id", logID, "resource");
}
11 changes: 11 additions & 0 deletions backend/src/utils/get-logbook-type.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default async function getLogbookType(logbookID, supabase) {
try {
const { data, error } = await supabase.from("logbooks").select().eq("id", logbookID);
if (error) {
throw new Error(error.message);
}
return data[0]['type'];
parkrafael marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
return { error: error.message };
}
}
22 changes: 22 additions & 0 deletions backend/src/utils/get-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export default async function getTable(supabase, table, param, value, type) {
try {
let data, error;
if (param == null && value == null) {
({ data, error } = await supabase.from(table).select());
} else if (param !== null && value !== null) {
({ data, error } = await supabase.from(table).select().eq(param, value));
} else {
throw new Error(`${param == null ? "param" : "value"} is empty at getTable`);
}
if (error) {
throw new Error(error.message);
}
if (type === "collection") {
return data
} else if (type === "resource") {
return data[0]
}
} catch (error) {
return { error: error.message };
}
}
12 changes: 12 additions & 0 deletions backend/src/utils/insert-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export default async function insertTable(supabase, table, values) {
try {
const { data, error } = await supabase.from(table).insert(values).select();
if (error) {
throw new Error(error.message);
} else {
return data[0];
}
} catch (error) {
return { error: error.message };
}
}
9 changes: 9 additions & 0 deletions backend/src/utils/parse-user-id.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default function parseUserID(token) {
try {
const parts = token.split(".");
const decodedPayload = JSON.parse(atob(parts[1]));
return decodedPayload["sub"];
} catch (error) {
return { error: error.message };
}
}
Loading