Skip to content
Open
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
56 changes: 3 additions & 53 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

83 changes: 41 additions & 42 deletions src/api/v1/streams.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,52 @@
import { Router, Request, Response } from "express";
import { StreamRepository, FindAllParams } from "../../repositories/streamRepository";
import { StreamRepository } from "../../repositories/streamRepository";
import { validate } from "../../middleware/validate";
import {
getStreamsQuerySchema,
uuidParamSchema,
} from "../../validation/schemas";

const router = Router();
const streamRepository = new StreamRepository();

// GET /api/v1/streams/:id
router.get("/:id", async (req: Request, res: Response) => {
try {
const { id } = req.params;

// Basic UUID validation (regex)
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(id)) {
return res.status(400).json({ error: "Invalid stream ID format" });
router.get(
"/:id",
validate({ params: uuidParamSchema }),
async (req: Request, res: Response) => {
try {
const { id } = req.params;

const stream = await streamRepository.findById(id);

if (!stream) {
return res.status(404).json({ error: "Stream not found" });
}

res.json(stream);
} catch (error) {
console.error("Error fetching stream:", error);
res.status(500).json({ error: "Internal server error" });
}

const stream = await streamRepository.findById(id);

if (!stream) {
return res.status(404).json({ error: "Stream not found" });
}

res.json(stream);
} catch (error) {
console.error("Error fetching stream:", error);
res.status(500).json({ error: "Internal server error" });
}
});
},
);

// GET /api/v1/streams
router.get("/", async (req: Request, res: Response) => {
try {
const { payer, recipient, status, limit, offset } = req.query;

const params: FindAllParams = {
payer: payer as string | undefined,
recipient: recipient as string | undefined,
status: status as FindAllParams["status"],
limit: limit ? parseInt(limit as string, 10) : undefined,
offset: offset ? parseInt(offset as string, 10) : undefined,
};

const result = await streamRepository.findAll(params);

res.json(result);
} catch (error) {
console.error("Error fetching streams:", error);
res.status(500).json({ error: "Internal server error" });
}
});
router.get(
"/",
validate({ query: getStreamsQuerySchema }),
async (req: Request, res: Response) => {
try {
const params = req.query;

const result = await streamRepository.findAll(params);

res.json(result);
} catch (error) {
console.error("Error fetching streams:", error);
res.status(500).json({ error: "Internal server error" });
}
},
);

export default router;
64 changes: 64 additions & 0 deletions src/middleware/validate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { Request, Response, NextFunction } from "express";
import { ZodError, ZodObject } from "zod";

type SchemaBundle = {
body?: ZodObject;
query?: ZodObject;
params?: ZodObject;
};

type ValidationError = {
path: string;
message: string;
};

export const validate =
(schemas: SchemaBundle) =>
(req: Request, res: Response, next: NextFunction) => {
const errors: ValidationError[] = [];

const validatePart = <T>(
schema: ZodObject | undefined,
data: unknown,
assign: (parsed: T) => void,
) => {
if (!schema) return;

const result = schema.safeParse(data);

if (!result.success) {
const formatted = formatZodErrors(result.error);
errors.push(...formatted);
} else {
assign(result.data as T);
}
};

validatePart<typeof req.body>(schemas.body, req.body, (data) => {
req.body = data;
});

validatePart<typeof req.query>(schemas.query, req.query, (data) => {
req.query = data as Request["query"];
});

validatePart<typeof req.params>(schemas.params, req.params, (data) => {
req.params = data as Request["params"];
});

if (errors.length > 0) {
return res.status(400).json({
error: "validation_error",
details: errors,
});
}

next();
};

function formatZodErrors(error: ZodError): ValidationError[] {
return error.issues.map((issue) => ({
path: issue.path.join("."),
message: issue.message,
}));
}
19 changes: 19 additions & 0 deletions src/validation/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { z } from "zod";

/**
* Streams query validation
*/
export const getStreamsQuerySchema = z.object({
payer: z.string().optional(),
recipient: z.string().optional(),
status: z.enum(["active", "paused", "cancelled", "completed"]).optional(),
limit: z.coerce.number().min(1).max(100).optional(),
offset: z.coerce.number().min(0).optional(),
});

/**
* UUID param validation
*/
export const uuidParamSchema = z.object({
id: z.string().uuid(),
});