Merge pull request #45 from detleph/feature-endpoints

Add more endpoints
This commit is contained in:
Stephan
2022-05-03 14:58:01 +02:00
committed by GitHub
14 changed files with 498 additions and 11 deletions
+9 -6
View File
@@ -10,6 +10,7 @@ export enum DataType {
PERMISSION_LEVEL = "'ELEVATED' | 'STANDARD'",
DATETIME = "ISOstring",
UUID = "string",
RESULT_SCHEMA = "result_schema",
}
interface Body {
@@ -64,6 +65,13 @@ export const genericError = {
},
};
export const NAME_ERROR = {
type: "error",
payload: {
message: "The name has to be at least 1 character long",
},
};
export function validateName(name: string) {
return name.length > 0;
}
@@ -106,12 +114,7 @@ export async function handleCreateByName(
}
if (!validateName(name)) {
return res.status(400).json({
type: "error",
payload: {
message: "The name has to be at least 1 character long",
},
});
return res.status(400).json(NAME_ERROR);
}
// Check if link object exsits
+189
View File
@@ -0,0 +1,189 @@
import { Prisma, Organisation, Admin, AdminLevel, Team } from "@prisma/client";
import { PrismaClientKnownRequestError, PrismaClientUnknownRequestError } from "@prisma/client/runtime";
import { Request, Response } from "express";
import prisma from "../lib/prisma";
import ForwardableError from "../Middleware/error/ForwardableError";
import NotFoundError from "../Middleware/error/NotFoundError";
import {
createInsufficientPermissionsError,
DataType,
generateError,
generateInvalidBodyError,
NAME_ERROR,
validateName,
} from "./common";
require("express-async-errors");
const basicDiscipline = {
pid: true,
name: true,
visual: { select: { pid: true, location: true } },
maxTeamSize: true,
minTeamSize: true,
event: { select: { pid: true, name: true } },
roles: { select: { pid: true, name: true } },
} as const;
const authenticatedDiscipline = {
...basicDiscipline,
teams: { select: { pid: true, name: true } },
} as const;
const elevatedDiscipline: Prisma.DisciplineFindManyArgs["select"] = {
...authenticatedDiscipline,
teams: { select: { pid: true, name: true, leaderEmail: true } },
};
export const _getAllDisciplines = async (
res: Response,
authenticated: boolean | undefined,
eventId: string | undefined
) => {
const disciplines = await prisma.discipline.findMany({
where: { event: { pid: eventId } },
select: !authenticated ? basicDiscipline : authenticatedDiscipline,
});
return res.status(200).json({
type: "success",
payload: {
disciplines,
},
});
};
interface GetAllDisciplinesSearchParams {
eventPid?: string;
}
export const getAllDisciplines = async (req: Request<{}, {}, {}, GetAllDisciplinesSearchParams>, res: Response) => {
return _getAllDisciplines(res, req.auth?.isAuthenticated, req.query.eventPid);
};
interface GetAllDisciplinesQueryParams {
eventPid: string;
}
export const GetAllDisciplinesWithParam = async (req: Request<GetAllDisciplinesQueryParams>, res: Response) => {
return _getAllDisciplines(res, req.auth?.isAuthenticated, req.params.eventPid);
};
interface GetDisciplineQueryParams {
pid: string;
}
export const getDiscipline = async (req: Request<GetDisciplineQueryParams>, res: Response) => {
const { pid } = req.params;
const discipline = await prisma.discipline.findUnique({
where: { pid },
select: !req.auth?.isAuthenticated
? basicDiscipline
: req.auth.permission_level !== "ELEVATED"
? authenticatedDiscipline
: elevatedDiscipline,
});
if (!discipline) {
throw new NotFoundError("discipline", pid);
}
return res.status(200).json({
type: "success",
payload: {
discipline: {
...discipline,
event: {
...discipline.event,
_links: [{ rel: "self", type: "GET", href: `/api/events/${discipline.event.pid}` }],
},
roles: discipline.roles.map((role) => ({
...role,
_links: [{ rel: "self", type: "GET", href: `/api/role/${role.pid}` }],
})),
...((discipline as any).teams
? (discipline as any).teams.map((team: Team) => ({
...team,
_links: [{ rel: "self", type: "GET", href: `/api/teams/${team.pid}` }],
}))
: {}),
},
},
});
};
interface CreateDisciplineBody {
name?: string;
minTeamSize?: number;
maxTeamSize?: number;
}
// require: auth(ELEVATED)
// at: POST /event/:eventPid/discipliens
export const createDiscipline = async (req: Request<{ eventPid: string }, {}, CreateDisciplineBody>, res: Response) => {
if (req.auth?.permission_level !== "ELEVATED") {
return res.status(403).json(createInsufficientPermissionsError());
}
const { name, minTeamSize, maxTeamSize } = req.body;
if (typeof name !== "string" || typeof minTeamSize !== "number" || typeof maxTeamSize !== "number") {
return res.status(400).json(
generateInvalidBodyError({
name: DataType.STRING,
minTeamSize: DataType.NUMBER,
maxTeamSize: DataType.NUMBER,
})
);
}
if (!validateName(name)) {
return res.status(400).json(NAME_ERROR);
}
try {
const discipline = await prisma.discipline.create({
data: { name, minTeamSize, maxTeamSize, event: { connect: { pid: req.params.eventPid } } },
select: {
pid: true,
name: true,
minTeamSize: true,
maxTeamSize: true,
event: { select: { pid: true, name: true } },
},
});
return res.status(201).json({ type: "success", payload: { discipline } });
} catch (e) {
if (e instanceof PrismaClientKnownRequestError && e.code === "P2025") {
return res.status(404).json(generateError(`Could not link to event with ID '${req.params.eventPid}'`));
}
throw e;
}
};
interface DeleteDisciplineQueryParams {
pid: string;
}
// requires: auth(ELEVATED)
export const deleteDiscipline = async (req: Request<DeleteDisciplineQueryParams>, res: Response) => {
if (req.auth?.permission_level !== "ELEVATED") {
res.status(403).json(createInsufficientPermissionsError());
}
const { pid } = req.params;
try {
await prisma.discipline.delete({ where: { pid } });
return res.status(204).end();
} catch (e) {
if (e instanceof PrismaClientKnownRequestError && e.code === "P2025") {
throw new NotFoundError("discipline", pid);
}
throw e;
}
};
+26 -2
View File
@@ -1,8 +1,8 @@
import { Admin } from "@prisma/client";
import { PrismaClientUnknownRequestError } from "@prisma/client/runtime";
import { PrismaClientKnownRequestError, PrismaClientUnknownRequestError } from "@prisma/client/runtime";
import { Request, Response } from "express";
import prisma from "../lib/prisma";
import { generateError, genericError, handleCreateByName } from "./common";
import { createInsufficientPermissionsError, generateError, genericError, handleCreateByName } from "./common";
const basicGroup = {
pid: true,
@@ -114,3 +114,27 @@ export const createGroup = async (req: Request<{ organisationPid: string }, {},
res
);
};
interface DeleteGroupQueryParams {
pid: string;
}
export const deleteGroup = async (req: Request<DeleteGroupQueryParams>, res: Response) => {
if (req.auth?.permission_level !== "ELEVATED") {
return res.status(403).json(createInsufficientPermissionsError());
}
const { pid } = req.params;
try {
prisma.group.delete({ where: { pid } });
return res.status(204).end();
} catch (e) {
if (e instanceof PrismaClientKnownRequestError && e.code === "P2025") {
return res.status(404).json(generateError(`The group with the ID ${pid} could not be found`));
}
throw e;
}
};
+125
View File
@@ -0,0 +1,125 @@
import { Prisma } from "@prisma/client";
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
import { Request, Response } from "express";
import prisma from "../lib/prisma";
import { DurationSchemaT, parseSchema, PointSchemaT } from "../lib/result_schema";
import NotFoundError from "../Middleware/error/NotFoundError";
import SchemaError from "../Middleware/error/SchemaError";
import {
createInsufficientPermissionsError,
DataType,
generateInvalidBodyError,
NAME_ERROR,
validateName,
} from "./common";
const roleSchema = {
name: true,
schema: true,
discipline: { select: { pid: true, name: true } },
visual: { select: { pid: true, location: true } },
} as const;
export const _getAllRoleSchemas = async (res: Response, disciplinePid: string | undefined) => {
const schemas = await prisma.roleSchema.findMany({
where: { discipline: { pid: disciplinePid } },
select: roleSchema,
});
return res.status(200).json({
type: "success",
payload: {
roleSchemas: schemas,
},
});
};
interface GetAllRoleSchemasSearchParams {
disciplinePid?: string;
}
export const getAllRoleSchemas = async (req: Request<{}, {}, {}, GetAllRoleSchemasSearchParams>, res: Response) => {
return _getAllRoleSchemas(res, req.query.disciplinePid);
};
interface GetAllRoleSchemasWithParamQueryParams {
organisationPid: string;
}
export const getAllRoleSchemasWithParam = async (
req: Request<GetAllRoleSchemasWithParamQueryParams>,
res: Response
) => {
return _getAllRoleSchemas(res, req.params.organisationPid);
};
interface GetRoleSchemaQueryParams {
pid: string;
}
export const getRoleSchema = async (req: Request<GetRoleSchemaQueryParams>, res: Response) => {
const { pid } = req.params;
const schema = await prisma.roleSchema.findUnique({ where: { pid }, select: roleSchema });
if (!schema) {
throw new NotFoundError("roleSchema", pid);
}
return res.status(200).json({
type: "success",
payload: {
roleSchema: {
...schema,
discipline: {
...schema.discipline,
_links: [{ rel: "self", type: "GET", href: `/api/disciplines/${schema.discipline.pid}` }],
},
},
},
});
};
interface CreateRoleSchemaBody {
name?: string;
schema?: any;
}
// at: POST /discipline/:disciplinePid/role-schemas
// requires: auth(ELEVATED)
export const createRoleSchema = async (
req: Request<{ disciplinePid: string }, {}, CreateRoleSchemaBody>,
res: Response
) => {
if (req.auth?.permission_level !== "ELEVATED") {
return res.status(403).json(createInsufficientPermissionsError());
}
const { name, schema: resultSchema } = req.body;
if (typeof name !== "string") {
return res.status(400).json(generateInvalidBodyError({ name: DataType.STRING, schema: DataType.RESULT_SCHEMA }));
}
if (!validateName(name)) {
return res.status(400).json(NAME_ERROR);
}
// Validate the result schema (Errors should be handled by the default error handler)
const validatedSchema = parseSchema(resultSchema);
try {
const schema = await prisma.roleSchema.create({
data: { name, schema: validatedSchema, discipline: { connect: { pid: req.params.disciplinePid } } },
select: roleSchema,
});
return res.status(201).json({ type: "success", payload: { roleSchema: schema } });
} catch (e) {
if (e instanceof PrismaClientKnownRequestError && e.code === "P2025") {
throw new NotFoundError("discipline", req.params.disciplinePid);
}
throw e;
}
};