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

Adding paid event routes #27

Open
wants to merge 5 commits into
base: events_ticketing_unification
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import vendingPlugin from "./routes/vending.js";
import * as dotenv from "dotenv";
import ssoManagementRoute from "./routes/sso.js";
import ticketsPlugin from "./routes/tickets.js";
import paidEventsPlugin from "./routes/paidEvents.js";
dotenv.config();

const now = () => Date.now();
Expand Down Expand Up @@ -71,6 +72,7 @@ async function init() {
async (api, _options) => {
api.register(protectedRoute, { prefix: "/protected" });
api.register(eventsPlugin, { prefix: "/events" });
api.register(paidEventsPlugin, { prefix: "/paidEvents" });
api.register(organizationsPlugin, { prefix: "/organizations" });
api.register(icalPlugin, { prefix: "/ical" });
api.register(ssoManagementRoute, { prefix: "/sso" });
Expand Down
290 changes: 290 additions & 0 deletions src/routes/paidEvents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,290 @@
import { FastifyPluginAsync, FastifyRequest } from "fastify";
import {
DynamoDBClient,
UpdateItemCommand,
QueryCommand,
ScanCommand,
ConditionalCheckFailedException,
} from "@aws-sdk/client-dynamodb";
import { genericConfig } from "../config.js";
import { unmarshall } from "@aws-sdk/util-dynamodb";
import { DatabaseFetchError } from "../errors/index.js";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

const dynamoclient = new DynamoDBClient({
region: genericConfig.AwsRegion,
});

type EventGetRequest = {
Params: { id: string };
Querystring: undefined;
Body: undefined;
};

type EventUpdateRequest = {
Params: { id: string };
Querystring: undefined;
Body: { attribute: string; value: string };
};

/*const updateJsonSchema = zodToJsonSchema(
z.object({
event_id: z.number(),
event_name: z.string(),
eventCost: z.record(z.number()),
eventDetails: z.optional(z.string()),
eventImage: z.optional(z.string()),
eventProps: z.record(z.string(), z.string()),
event_capacity: z.number(),
event_sales_active_utc: z.string(),
event_time: z.number(),
member_price: z.optional(z.string()),
nonmember_price: z.optional(z.string()),
tickets_sold: z.number()
})
)*/

const responseJsonSchema = zodToJsonSchema(
z.object({
id: z.string(),
resource: z.string(),
}),
);

const paidEventsPlugin: FastifyPluginAsync = async (fastify, _options) => {
fastify.get("/", (request, reply) => {
reply.send({ Status: "Up" });
});
fastify.get("/ticketEvents", async (request, reply) => {
try {
const response = await dynamoclient.send(
new ScanCommand({
TableName: genericConfig.TicketMetadataTableName,
}),
);
const items = response.Items?.map((item) => unmarshall(item));
reply
.header(
"cache-control",
"public, max-age=7200, stale-while-revalidate=900, stale-if-error=86400",
)
.send(items);
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error("Failed" + e.toString());
} else {
request.log.error(`Failed to get from DynamoDB. ${e}`);
}
throw new DatabaseFetchError({
message: "Failed to get events from Dynamo table.",
});
}
});
fastify.get("/merchEvents", async (request, reply) => {
try {
const response = await dynamoclient.send(
new ScanCommand({
TableName: genericConfig.MerchStoreMetadataTableName,
}),
);
const items = response.Items?.map((item) => unmarshall(item));
reply
.header(
"cache-control",
"public, max-age=7200, stale-while-revalidate=900, stale-if-error=86400",
)
.send(items);
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error("Failed" + e.toString());
} else {
request.log.error(`Failed to get from DynamoDB. ${e}`);
}
throw new DatabaseFetchError({
message: "Failed to get events from Dynamo table.",
});
}
});

//helper get no validation
fastify.get<EventGetRequest>(
"/ticketEvents/:id",
async (request: FastifyRequest<EventGetRequest>, reply) => {
const id = request.params.id;
try {
const response = await dynamoclient.send(
new QueryCommand({
TableName: genericConfig.TicketMetadataTableName,
KeyConditionExpression: "event_id = :id",
ExpressionAttributeValues: {
":id": { S: 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.",
});
}
},
);

fastify.get<EventGetRequest>(
"/merchEvents/:id",
async (request: FastifyRequest<EventGetRequest>, reply) => {
const id = request.params.id;
try {
const response = await dynamoclient.send(
new QueryCommand({
TableName: genericConfig.MerchStoreMetadataTableName,
KeyConditionExpression: "item_id = :id",
ExpressionAttributeValues: {
":id": { S: 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.",
});
}
},
);

fastify.put<EventUpdateRequest>(
"/ticketEvents/:id",
{
schema: {
response: { 200: responseJsonSchema },
},
/*onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [AppRoles.EVENTS_MANAGER]);
},*/ //Validation taken off for testing
},
async (request: FastifyRequest<EventUpdateRequest>, reply) => {
try {
const id = request.params.id;
const attribute = request.body.attribute;
const value = request.body.value;

let valueExpression;
const temp = Number(value);
if (isNaN(temp)) {
valueExpression = { S: value };
} else {
valueExpression = { N: value };
}

const _response = await dynamoclient.send(
new UpdateItemCommand({
TableName: genericConfig.TicketMetadataTableName,
Key: {
event_id: { S: id },
},
ConditionExpression: "attribute_exists(#attr)",
UpdateExpression: "SET #attr = :value",
ExpressionAttributeNames: {
"#attr": attribute,
},
ExpressionAttributeValues: {
":value": valueExpression,
},
}),
);
reply.send({
id: id,
resource: `/api/v1/paidEvents/ticketEvents/${id}`,
});
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error("Failed to get from DynamoDB: " + e.toString());
}
if (e instanceof ConditionalCheckFailedException) {
request.log.error("Attribute does not exist");
}
throw new DatabaseFetchError({
message: "Failed to get event from Dynamo table.",
});
}
},
);

//Multiple attribute udpates...

fastify.put<EventUpdateRequest>(
"/merchEvents/:id",
{
schema: {
response: { 200: responseJsonSchema },
},
/*onRequest: async (request, reply) => {
await fastify.authorize(request, reply, [AppRoles.EVENTS_MANAGER]);
},*/ //Validatison taken off for testing
},
async (request: FastifyRequest<EventUpdateRequest>, reply) => {
try {
const id = request.params.id;
const attribute = request.body.attribute;
const value = request.body.value;

let valueExpression;
const num = Number(value);
if (isNaN(num)) {
valueExpression = { S: value };
} else {
valueExpression = { N: value };
}

const _response = await dynamoclient.send(
new UpdateItemCommand({
TableName: genericConfig.MerchStoreMetadataTableName,
Key: {
item_id: { S: id },
},
ConditionExpression: "attribute_exists(#attr)",
UpdateExpression: "SET #attr = :value",
ExpressionAttributeNames: {
"#attr": attribute,
},
ExpressionAttributeValues: {
":value": valueExpression,
},
}),
);
reply.send({
id: id,
resource: `/api/v1/paidEvents/merchEvents/${id}`,
});
} catch (e: unknown) {
if (e instanceof Error) {
request.log.error("Failed to get from DynamoDB: " + e.toString());
}
if (e instanceof ConditionalCheckFailedException) {
request.log.error("Attribute does not exist");
}
throw new DatabaseFetchError({
message: "Failed to get event from Dynamo table.",
});
}
},
);
};

export default paidEventsPlugin;
2 changes: 1 addition & 1 deletion tests/unit/entraInviteUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ vi.mock("../../src/functions/entraId.js", () => {
getEntraIdToken: vi.fn().mockImplementation(async () => {
return "ey.test.token";
}),
addToTenant: vi.fn().mockImplementation(async (email) => {
addToTenant: vi.fn().mockImplementation(async (_email) => {
return { success: true, email: "[email protected]" };
}),
};
Expand Down
Loading
Loading