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

clean up naming scheme and add ID to get all request #2

Merged
merged 5 commits into from
Aug 22, 2024
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
14 changes: 10 additions & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { AppRoles, RunEnvironment } from "./roles.js";
import { OriginFunction } from "@fastify/cors";

type GroupRoleMapping = Record<string, AppRoles[]>;
type AzureRoleMapping = Record<string, AppRoles[]>;
// From @fastify/cors
type ArrayOfValueOrArray<T> = Array<ValueOrArray<T>>;
type OriginType = string | boolean | RegExp;
type ValueOrArray<T> = T | ArrayOfValueOrArray<T>;

type GroupRoleMapping = Record<string, readonly AppRoles[]>;
type AzureRoleMapping = Record<string, readonly AppRoles[]>;

export type ConfigType = {
GroupRoleMapping: GroupRoleMapping;
AzureRoleMapping: AzureRoleMapping;
ValidCorsOrigins: (string | RegExp)[];
ValidCorsOrigins: ValueOrArray<OriginType> | OriginFunction;
AadValidClientId: string;
};

Expand Down Expand Up @@ -60,6 +66,6 @@ const environmentConfig: EnvironmentConfigType = {
],
AadValidClientId: "5e08cf0f-53bb-4e09-9df2-e9bdc3467296",
},
} as const;
};

export { genericConfig, environmentConfig };
119 changes: 104 additions & 15 deletions src/routes/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { OrganizationList } from "../orgs.js";
import {
DeleteItemCommand,
DynamoDBClient,
PutItemCommand,
ScanCommand,
Expand All @@ -18,7 +19,7 @@ import moment from "moment-timezone";

const repeatOptions = ["weekly", "biweekly"] as const;

const baseBodySchema = z.object({
const baseSchema = z.object({
title: z.string().min(1),
description: z.string().min(1),
start: z.string(),
Expand All @@ -30,16 +31,20 @@ const baseBodySchema = z.object({
paidEventId: z.optional(z.string().min(1)),
});

const requestBodySchema = baseBodySchema
.extend({
repeats: z.optional(z.enum(repeatOptions)),
repeatEnds: z.string().optional(),
})
.refine((data) => (data.repeatEnds ? data.repeats !== undefined : true), {
const requestSchema = baseSchema.extend({
repeats: z.optional(z.enum(repeatOptions)),
repeatEnds: z.string().optional(),
});

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const postRequestSchema = requestSchema.refine(
(data) => (data.repeatEnds ? data.repeats !== undefined : true),
{
message: "repeats is required when repeatEnds is defined",
});
},
);

type EventPostRequest = z.infer<typeof requestBodySchema>;
type EventPostRequest = z.infer<typeof postRequestSchema>;

const responseJsonSchema = zodToJsonSchema(
z.object({
Expand All @@ -49,9 +54,15 @@ const responseJsonSchema = zodToJsonSchema(
);

// GET
const getResponseBodySchema = z.array(requestBodySchema);
const getResponseJsonSchema = zodToJsonSchema(getResponseBodySchema);
export type EventGetResponse = z.infer<typeof getResponseBodySchema>;
const getEventSchema = requestSchema.extend({
id: z.string(),
});

export type EventGetResponse = z.infer<typeof getEventSchema>;
const getEventJsonSchema = zodToJsonSchema(getEventSchema);

const getEventsSchema = z.array(getEventSchema);
export type EventsGetResponse = z.infer<typeof getEventsSchema>;
type EventsGetQueryParams = { upcomingOnly?: boolean };

const dynamoClient = new DynamoDBClient({
Expand All @@ -66,7 +77,7 @@ const eventsPlugin: FastifyPluginAsync = async (fastify, _options) => {
response: { 200: responseJsonSchema },
},
preValidation: async (request, reply) => {
await fastify.zodValidateBody(request, reply, requestBodySchema);
await fastify.zodValidateBody(request, reply, postRequestSchema);
},
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [AppRoles.MANAGER]);
Expand Down Expand Up @@ -101,6 +112,84 @@ const eventsPlugin: FastifyPluginAsync = async (fastify, _options) => {
}
},
);
type EventGetRequest = {
Params: { id: string };
Querystring: undefined;
Body: undefined;
};
fastify.get<EventGetRequest>(
"/:id",
{
schema: {
response: { 200: getEventJsonSchema },
},
},
async (request: FastifyRequest<EventGetRequest>, reply) => {
const id = request.params.id;
try {
const response = await dynamoClient.send(
new ScanCommand({
TableName: genericConfig.DynamoTableName,
FilterExpression: "#id = :id",
ExpressionAttributeNames: {
"#id": "id",
},
ExpressionAttributeValues: marshall({ ":id": id }),
}),
);
const items = response.Items?.map((item) => unmarshall(item));
if (items?.length !== 1) {
throw new Error("Event not found");
}
reply.send(items[0]);
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error("Failed to get from DynamoDB: " + e.toString());
}
throw new DatabaseFetchError({
message: "Failed to get event from Dynamo table.",
});
}
},
);
type EventDeleteRequest = {
Params: { id: string };
Querystring: undefined;
Body: undefined;
};
fastify.delete<EventDeleteRequest>(
"/:id",
{
schema: {
response: { 200: responseJsonSchema },
},
onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [AppRoles.MANAGER]);
},
},
async (request: FastifyRequest<EventDeleteRequest>, reply) => {
const id = request.params.id;
try {
await dynamoClient.send(
new DeleteItemCommand({
TableName: genericConfig.DynamoTableName,
Key: marshall({ id }),
}),
);
reply.send({
id,
resource: `/api/v1/event/${id}`,
});
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error("Failed to delete from DynamoDB: " + e.toString());
}
throw new DatabaseInsertError({
message: "Failed to delete event from Dynamo table.",
});
}
},
);
type EventsGetRequest = {
Body: undefined;
Querystring?: EventsGetQueryParams;
Expand All @@ -112,7 +201,7 @@ const eventsPlugin: FastifyPluginAsync = async (fastify, _options) => {
querystring: {
upcomingOnly: { type: "boolean" },
},
response: { 200: getResponseJsonSchema },
response: { 200: getEventsSchema },
},
},
async (request: FastifyRequest<EventsGetRequest>, reply) => {
Expand All @@ -123,7 +212,7 @@ const eventsPlugin: FastifyPluginAsync = async (fastify, _options) => {
);
const items = response.Items?.map((item) => unmarshall(item));
const currentTimeChicago = moment().tz("America/Chicago");
let parsedItems = getResponseBodySchema.parse(items);
let parsedItems = getEventsSchema.parse(items);
if (upcomingOnly) {
parsedItems = parsedItems.filter((item) => {
try {
Expand Down
4 changes: 2 additions & 2 deletions tests/live/events.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, test } from "vitest";
import { InternalServerError } from "../../src/errors/index.js";
import { EventGetResponse } from "../../src/routes/events.js";
import { EventsGetResponse } from "../../src/routes/events.js";

const appKey = process.env.APPLICATION_KEY;
if (!appKey) {
Expand All @@ -12,6 +12,6 @@ const baseEndpoint = `https://${appKey}.aws.qa.acmuiuc.org`;
test("getting events", async () => {
const response = await fetch(`${baseEndpoint}/api/v1/events`);
expect(response.status).toBe(200);
const responseJson = (await response.json()) as EventGetResponse;
const responseJson = (await response.json()) as EventsGetResponse;
expect(responseJson.length).greaterThan(0);
});
15 changes: 2 additions & 13 deletions tests/unit/events.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { afterAll, expect, test, beforeEach, vi } from "vitest";
import {
ScanCommand,
DynamoDBClient,
PutItemCommand,
} from "@aws-sdk/client-dynamodb";
import { ScanCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { mockClient } from "aws-sdk-client-mock";
import init from "../../src/index.js";
import { EventGetResponse } from "../../src/routes/events.js";
Expand All @@ -12,16 +8,9 @@ import {
dynamoTableDataUnmarshalled,
dynamoTableDataUnmarshalledUpcomingOnly,
} from "./mockEventData.testdata.js";
import { createJwt } from "./auth.test.js";
import {
GetSecretValueCommand,
SecretsManagerClient,
} from "@aws-sdk/client-secrets-manager";
import { secretJson, secretObject } from "./secret.testdata.js";
import supertest from "supertest";
import { secretObject } from "./secret.testdata.js";

const ddbMock = mockClient(DynamoDBClient);
const smMock = mockClient(SecretsManagerClient);
const jwt_secret = secretObject["jwt_key"];
vi.stubEnv("JwtSigningKey", jwt_secret);

Expand Down
2 changes: 0 additions & 2 deletions tests/unit/mockEventData.testdata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,13 @@ const dynamoTableData = [

const dynamoTableDataUnmarshalled = dynamoTableData.map((x: any) => {
const temp = unmarshall(x);
delete temp.id;
delete temp.createdBy;
return temp;
});

const dynamoTableDataUnmarshalledUpcomingOnly = dynamoTableData
.map((x: any) => {
const temp = unmarshall(x);
delete temp.id;
delete temp.createdBy;
return temp;
})
Expand Down
Loading