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

Add handler testing #134

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
10 changes: 6 additions & 4 deletions app/server/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { HELLO_WORLD, signInInputSchema, signUpInputSchema } from "@bookery/shared";
import { signinHandler, signupHandler } from "./handlers/auth-handlers";

import { HELLO_WORLD } from "@bookery/shared";
import { Service } from "./service/services";
import express from "express";
import { forExpress } from "./handlers/handler";
import { getCoachHandler } from "./handlers/coach-handler";
import session from "express-session";
import { z } from "zod";

export function buildApp(service: Service) {
const app = express();
Expand All @@ -16,9 +18,9 @@ export function buildApp(service: Service) {
);
app.use(express.json());

app.post("/api/auth/signup", signupHandler(service.auth));
app.post("/api/auth/signin", signinHandler(service.auth));
app.get("/api/coach/:id", getCoachHandler(service.coach));
app.post("/api/auth/signup", forExpress(signupHandler(service.auth), {requestBodySchema: signUpInputSchema}));
app.post("/api/auth/signin", forExpress(signinHandler(service.auth), {requestBodySchema: signInInputSchema}));
app.get("/api/coach/:id", forExpress(getCoachHandler(service.coach), {paramsSchema: z.object({id: z.string()})}));

app.get("/", (req, res) => {
res.send(HELLO_WORLD);
Expand Down
62 changes: 21 additions & 41 deletions app/server/src/handlers/auth-handlers.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,31 @@
import { NextFunction, Request, Response } from "express";
import { signInInputSchema, signUpInputSchema } from "@bookery/shared";
import { SignInInput, SignUpInput } from "@bookery/shared";

import { AuthService } from "../service/auth-service";
import { Context } from "./handler";

export const signupHandler =
(auth: AuthService) =>
async (req: Request, res: Response, next: NextFunction) => {
try {
const inputParseResult = signUpInputSchema.safeParse(req.body);
if (!inputParseResult.success) {
return res.sendStatus(400);
}
const coach = await auth.signUp(inputParseResult.data);
req.session.coach = coach;
return res.send({ success: true });
} catch (e) {
next(e);
}
};
async (context: Context<SignUpInput>) => {
const coach = await auth.signUp(context.body);
context.setSession(coach);
return {
status: 200,
body: { success: true },
};
}

export const signinHandler =
(auth: AuthService) =>
async (req: Request, res: Response, next: NextFunction) => {
async (context: Context<SignInInput>) => {
try {
const inputParseResult = signInInputSchema.safeParse(req.body);
if (!inputParseResult.success) {
return res.sendStatus(400);
}
await auth
.signIn(inputParseResult.data)
.then((coach) => (req.session.coach = coach))
.then(() => res.send({ success: true }))
.catch(() => handleFailedSignIn(req, res));
} catch (e) {
next(e);
const coach = await auth.signIn(context.body);
context.setSession(coach);
return {
status: 200,
body: { success: true },
};
} catch {
await context.destroySession();
return { status: 401, body: { success: false } };
}
};

async function handleFailedSignIn(req: Request, res: Response) {
await new Promise((resolve, reject) => {
req.session.destroy((err) => {
if (err) {
reject(err);
} else {
resolve(undefined);
}
});
});
res.sendStatus(401);
}
}
29 changes: 13 additions & 16 deletions app/server/src/handlers/coach-handler.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import { NextFunction, Request, Response } from "express";

import { CoachService } from "../service/coach-service";
import { Context } from "./handler";

export const getCoachHandler =
(coachService: CoachService) =>
async (req: Request, res: Response, next: NextFunction) => {
try {
const {id} = req.params;
if (id == null) {
throw new Error("id is missing in URL params.");
}
if (id != req.session.coach?.id) {
return res.sendStatus(403);
}
const coach = await coachService.getCoach(id);
return res.send({ coach });
} catch (e) {
next(e);
async (context: Context<unknown, {id: string}>) => {
if (context.params.id !== context.session?.id) {
return {
status: 403,
body: "Forbidden",
};
}
}
const coach = await coachService.getCoach(context.params.id);
return {
status: 200,
body: { coach },
};
};
61 changes: 61 additions & 0 deletions app/server/src/handlers/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Coach } from "@bookery/database";
import { RequestHandler } from "express";
import { z } from "zod";

type ResponseSpec = {
status: number;
body?: unknown;
};

type HandlerOptions<TBodySchema extends z.ZodTypeAny, TParamsSchema extends z.ZodTypeAny> = {
requestBodySchema?: TBodySchema;
paramsSchema?: TParamsSchema;
};

export type Context<TBody=unknown, TParams=unknown> = {
body: TBody;
params: TParams;
session?: Coach;
setSession: (coach: Coach) => void;
destroySession: () => Promise<void>;
};

export type Handler<TBody, TParams> = (context: Context<TBody, TParams>) => Promise<ResponseSpec>;

export const forExpress = <TBodySchema extends z.ZodTypeAny = z.ZodUnknown, TParamsSchema extends z.ZodTypeAny = z.ZodUnknown>(
handler: Handler<z.infer<TBodySchema>, z.infer<TParamsSchema>>,
options: HandlerOptions<TBodySchema, TParamsSchema>,
) => {
const expressHandler: RequestHandler = async (req, res, next) => {
try {
const paramsParseResult = options.paramsSchema?.safeParse(req.params);
if (paramsParseResult?.success === false) {
return res.sendStatus(400);
}
const bodyParseResult = options.requestBodySchema?.safeParse(req.body);
if (bodyParseResult?.success === false) {
return res.sendStatus(400);
}
const resSpec = await handler({
body: bodyParseResult?.data,
params: paramsParseResult?.data,
session: req.session.coach,
setSession: (coach) => { req.session.coach = coach },
destroySession: () => new Promise((resolve, reject) => {
req.session.destroy((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
}),
});
return res.status(resSpec.status).send(resSpec.body);
} catch (e) {
next(e);
}
};

return expressHandler;
};