fix architecture and write new tests
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { Response } from 'express'
|
||||
import { z } from 'zod'
|
||||
import { AppError, ConflictError, ForbiddenError, NotFoundError, UnauthorizedError, ValidationError } from './index'
|
||||
import { errorMiddleware } from './errorMiddleware'
|
||||
|
||||
function createResponseStub() {
|
||||
const res = {
|
||||
status: vi.fn(),
|
||||
json: vi.fn(),
|
||||
}
|
||||
|
||||
res.status.mockReturnValue(res)
|
||||
res.json.mockReturnValue(res)
|
||||
|
||||
return res as unknown as Response & typeof res
|
||||
}
|
||||
|
||||
function handle(error: unknown) {
|
||||
const res = createResponseStub()
|
||||
errorMiddleware(error, {} as any, res, vi.fn())
|
||||
return res
|
||||
}
|
||||
|
||||
describe('AppError subclasses', () => {
|
||||
it.each([
|
||||
[new ValidationError('Bad payload'), 400, 'validation_error'],
|
||||
[new UnauthorizedError(), 401, 'unauthorized'],
|
||||
[new ForbiddenError(), 403, 'forbidden'],
|
||||
[new NotFoundError(), 404, 'not_found'],
|
||||
[new ConflictError(), 409, 'conflict'],
|
||||
])('sets stable status and error code for %s', (error, statusCode, code) => {
|
||||
expect(error).toBeInstanceOf(AppError)
|
||||
expect(error.statusCode).toBe(statusCode)
|
||||
expect(error.error).toBe(code)
|
||||
})
|
||||
})
|
||||
|
||||
describe('errorMiddleware', () => {
|
||||
it('normalizes Zod errors into validation responses', () => {
|
||||
const result = z.object({ email: z.string().email() }).safeParse({ email: 'not-an-email' })
|
||||
expect(result.success).toBe(false)
|
||||
|
||||
const res = handle(result.success ? new Error('unexpected') : result.error)
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(400)
|
||||
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
|
||||
error: 'validation_error',
|
||||
message: 'Invalid request body',
|
||||
statusCode: 400,
|
||||
issues: expect.any(Array),
|
||||
}))
|
||||
})
|
||||
|
||||
it('normalizes Prisma not found errors', () => {
|
||||
const res = handle({ code: 'P2025' })
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(404)
|
||||
expect(res.json).toHaveBeenCalledWith({
|
||||
error: 'not_found',
|
||||
message: 'Resource not found',
|
||||
statusCode: 404,
|
||||
})
|
||||
})
|
||||
|
||||
it('normalizes Prisma unique constraint errors', () => {
|
||||
const res = handle({ code: 'P2002' })
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(409)
|
||||
expect(res.json).toHaveBeenCalledWith({
|
||||
error: 'conflict',
|
||||
message: 'A resource with this value already exists',
|
||||
statusCode: 409,
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves AppError metadata in the response body', () => {
|
||||
const res = handle(new AppError('Plan required', 402, 'payment_required', { requiredPlan: 'PRO' }))
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(402)
|
||||
expect(res.json).toHaveBeenCalledWith({
|
||||
error: 'payment_required',
|
||||
message: 'Plan required',
|
||||
statusCode: 402,
|
||||
requiredPlan: 'PRO',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to a 500 internal error response', () => {
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
|
||||
const res = handle(new Error('boom'))
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(500)
|
||||
expect(res.json).toHaveBeenCalledWith({ error: 'internal_error', message: 'Internal server error', statusCode: 500, requestId: undefined })
|
||||
|
||||
spy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -1,29 +1,48 @@
|
||||
import { Request, Response, NextFunction } from 'express'
|
||||
import { AppError } from './index'
|
||||
|
||||
export function errorMiddleware(err: any, _req: Request, res: Response, _next: NextFunction) {
|
||||
function withRequestId(req: Request, payload: Record<string, unknown>) {
|
||||
return { ...payload, requestId: req.requestId }
|
||||
}
|
||||
|
||||
export function errorMiddleware(err: any, req: Request, res: Response, _next: NextFunction) {
|
||||
if (err.name === 'ZodError') {
|
||||
return res.status(400).json({ error: 'validation_error', message: 'Invalid request body', issues: err.issues, statusCode: 400 })
|
||||
return res.status(400).json(withRequestId(req, {
|
||||
error: 'validation_error',
|
||||
message: 'Invalid request body',
|
||||
issues: err.issues,
|
||||
statusCode: 400,
|
||||
}))
|
||||
}
|
||||
|
||||
if (err.code === 'P2025') {
|
||||
return res.status(404).json({ error: 'not_found', message: 'Resource not found', statusCode: 404 })
|
||||
return res.status(404).json(withRequestId(req, { error: 'not_found', message: 'Resource not found', statusCode: 404 }))
|
||||
}
|
||||
|
||||
if (err.code === 'P2002') {
|
||||
return res.status(409).json({ error: 'conflict', message: 'A resource with this value already exists', statusCode: 409 })
|
||||
return res.status(409).json(withRequestId(req, { error: 'conflict', message: 'A resource with this value already exists', statusCode: 409 }))
|
||||
}
|
||||
|
||||
if (err instanceof AppError) {
|
||||
if (err.statusCode >= 500) console.error('[API Error]', err)
|
||||
return res.status(err.statusCode).json({ error: err.error, message: err.message, statusCode: err.statusCode, ...err.data })
|
||||
if (err.statusCode >= 500) console.error('[API Error]', { requestId: req.requestId, err })
|
||||
return res.status(err.statusCode).json(withRequestId(req, {
|
||||
error: err.error,
|
||||
message: err.statusCode >= 500 ? 'Internal server error' : err.message,
|
||||
statusCode: err.statusCode,
|
||||
...(err.statusCode >= 500 ? {} : err.data),
|
||||
}))
|
||||
}
|
||||
|
||||
const statusCode = err.statusCode ?? 500
|
||||
const message = err.message ?? 'Internal server error'
|
||||
const code = err.code ?? 'internal_error'
|
||||
const statusCode = typeof err.statusCode === 'number' ? err.statusCode : 500
|
||||
const safeStatusCode = statusCode >= 400 && statusCode < 600 ? statusCode : 500
|
||||
|
||||
if (statusCode >= 500) console.error('[API Error]', err)
|
||||
if (safeStatusCode >= 500) {
|
||||
console.error('[API Error]', { requestId: req.requestId, err })
|
||||
}
|
||||
|
||||
res.status(statusCode).json({ error: code, message, statusCode })
|
||||
res.status(safeStatusCode).json(withRequestId(req, {
|
||||
error: safeStatusCode >= 500 ? 'internal_error' : (err.code ?? 'request_error'),
|
||||
message: safeStatusCode >= 500 ? 'Internal server error' : (err.message ?? 'Request failed'),
|
||||
statusCode: safeStatusCode,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { Response } from 'express'
|
||||
import { created, noContent, ok } from './index'
|
||||
|
||||
function createResponseStub() {
|
||||
const res = {
|
||||
status: vi.fn(),
|
||||
json: vi.fn(),
|
||||
end: vi.fn(),
|
||||
}
|
||||
|
||||
res.status.mockReturnValue(res)
|
||||
res.json.mockReturnValue(res)
|
||||
res.end.mockReturnValue(res)
|
||||
|
||||
return res as unknown as Response & typeof res
|
||||
}
|
||||
|
||||
describe('http/respond helpers', () => {
|
||||
it('ok responds with the expected data envelope', () => {
|
||||
const res = createResponseStub()
|
||||
const payload = { id: 'vehicle_1', name: 'Dacia Logan' }
|
||||
|
||||
ok(res, payload)
|
||||
|
||||
expect(res.status).not.toHaveBeenCalled()
|
||||
expect(res.json).toHaveBeenCalledWith({ data: payload })
|
||||
})
|
||||
|
||||
it('created responds with status 201 and the expected data envelope', () => {
|
||||
const res = createResponseStub()
|
||||
const payload = { id: 'reservation_1' }
|
||||
|
||||
created(res, payload)
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(201)
|
||||
expect(res.json).toHaveBeenCalledWith({ data: payload })
|
||||
})
|
||||
|
||||
it('noContent responds with status 204 and no body', () => {
|
||||
const res = createResponseStub()
|
||||
|
||||
noContent(res)
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(204)
|
||||
expect(res.end).toHaveBeenCalledWith()
|
||||
expect(res.json).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,14 @@
|
||||
import path from 'path'
|
||||
import multer from 'multer'
|
||||
import { ValidationError } from '../errors'
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
|
||||
const ALLOWED_IMAGE_TYPES = new Map<string, string[]>([
|
||||
['image/jpeg', ['.jpg', '.jpeg']],
|
||||
['image/png', ['.png']],
|
||||
['image/webp', ['.webp']],
|
||||
['image/gif', ['.gif']],
|
||||
])
|
||||
|
||||
/**
|
||||
* Shared multer instance used by all upload endpoints.
|
||||
@@ -9,26 +16,68 @@ const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
|
||||
*/
|
||||
export const imageUpload = multer({
|
||||
storage: multer.memoryStorage(),
|
||||
limits: { fileSize: MAX_FILE_SIZE },
|
||||
limits: { fileSize: MAX_FILE_SIZE, files: 20 },
|
||||
})
|
||||
|
||||
type DetectedFile = { mime: string; ext: string }
|
||||
|
||||
export function detectImageType(buffer: Buffer): DetectedFile | null {
|
||||
if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
|
||||
return { mime: 'image/jpeg', ext: '.jpg' }
|
||||
}
|
||||
|
||||
if (
|
||||
buffer.length >= 8 &&
|
||||
buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4e && buffer[3] === 0x47 &&
|
||||
buffer[4] === 0x0d && buffer[5] === 0x0a && buffer[6] === 0x1a && buffer[7] === 0x0a
|
||||
) {
|
||||
return { mime: 'image/png', ext: '.png' }
|
||||
}
|
||||
|
||||
if (buffer.length >= 12 && buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP') {
|
||||
return { mime: 'image/webp', ext: '.webp' }
|
||||
}
|
||||
|
||||
if (buffer.length >= 6) {
|
||||
const sig = buffer.subarray(0, 6).toString('ascii')
|
||||
if (sig === 'GIF87a' || sig === 'GIF89a') return { mime: 'image/gif', ext: '.gif' }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function assertSafeImageContent(file: Express.Multer.File) {
|
||||
const detected = detectImageType(file.buffer)
|
||||
if (!detected || !ALLOWED_IMAGE_TYPES.has(detected.mime)) {
|
||||
throw new ValidationError('Unsupported or spoofed image file')
|
||||
}
|
||||
|
||||
if (file.mimetype !== detected.mime) {
|
||||
throw new ValidationError(`MIME type does not match file content for "${file.originalname}"`)
|
||||
}
|
||||
|
||||
const ext = path.extname(file.originalname).toLowerCase()
|
||||
const allowedExtensions = ALLOWED_IMAGE_TYPES.get(detected.mime) ?? []
|
||||
if (ext && !allowedExtensions.includes(ext)) {
|
||||
throw new ValidationError(`File extension does not match file content for "${file.originalname}"`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a file was provided and is an image MIME type.
|
||||
* Call inside the route handler after the multer middleware runs.
|
||||
* Asserts that a file was provided and is an image by content, not by client claims.
|
||||
*/
|
||||
export function assertImageFile(
|
||||
file: Express.Multer.File | undefined,
|
||||
fieldLabel = 'file',
|
||||
): asserts file is Express.Multer.File {
|
||||
if (!file) throw new ValidationError(`A ${fieldLabel} is required`)
|
||||
if (!file.mimetype.startsWith('image/')) throw new ValidationError('Only image uploads are supported')
|
||||
assertSafeImageContent(file)
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that at least one file was provided and all files are images.
|
||||
* Asserts that at least one file was provided and all files are image content.
|
||||
*/
|
||||
export function assertImageFiles(files: Express.Multer.File[], fieldLabel = 'photos'): void {
|
||||
if (!files || files.length === 0) throw new ValidationError(`At least one ${fieldLabel} file is required`)
|
||||
const nonImage = files.find((f) => !f.mimetype.startsWith('image/'))
|
||||
if (nonImage) throw new ValidationError(`All uploaded files must be images — "${nonImage.originalname}" is not`)
|
||||
for (const file of files) assertSafeImageContent(file)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ValidationError } from '../errors'
|
||||
import { assertImageFile, assertImageFiles } from './index'
|
||||
|
||||
const file = (overrides: Partial<Express.Multer.File> = {}) => ({
|
||||
fieldname: 'file',
|
||||
originalname: 'photo.jpg',
|
||||
encoding: '7bit',
|
||||
mimetype: 'image/jpeg',
|
||||
size: 123,
|
||||
buffer: Buffer.from([0xff, 0xd8, 0xff, 0xdb]),
|
||||
stream: undefined as any,
|
||||
destination: '',
|
||||
filename: '',
|
||||
path: '',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('upload assertions', () => {
|
||||
it('accepts a single image file and narrows the route input', () => {
|
||||
expect(() => assertImageFile(file())).not.toThrow()
|
||||
})
|
||||
|
||||
it('rejects missing single file uploads with a field-specific error', () => {
|
||||
expect(() => assertImageFile(undefined, 'license image')).toThrow(ValidationError)
|
||||
expect(() => assertImageFile(undefined, 'license image')).toThrow('A license image is required')
|
||||
})
|
||||
|
||||
it('rejects non-image single file uploads', () => {
|
||||
expect(() => assertImageFile(file({ mimetype: 'application/pdf', originalname: 'license.pdf' }))).toThrow('MIME type does not match file content')
|
||||
})
|
||||
|
||||
it('accepts multiple image files and rejects empty or mixed batches', () => {
|
||||
expect(() => assertImageFiles([file({ originalname: 'front.png', mimetype: 'image/png', buffer: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) })])).not.toThrow()
|
||||
expect(() => assertImageFiles([], 'inspection photos')).toThrow('At least one inspection photos file is required')
|
||||
expect(() => assertImageFiles([
|
||||
file({ originalname: 'front.png', mimetype: 'image/png', buffer: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) }),
|
||||
file({ originalname: 'report.pdf', mimetype: 'application/pdf', buffer: Buffer.from('%PDF') }),
|
||||
])).toThrow('Unsupported or spoofed image file')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { Request } from 'express'
|
||||
import { z } from 'zod'
|
||||
import { parseBody, parseParams, parseQuery } from './index'
|
||||
|
||||
describe('http/validate parsers', () => {
|
||||
it('parseBody returns typed and coerced request body values', () => {
|
||||
const schema = z.object({ seats: z.coerce.number().int().min(1), brand: z.string().min(1) })
|
||||
const req = { body: { seats: '5', brand: 'Toyota' } } as Request
|
||||
|
||||
expect(parseBody(schema, req)).toEqual({ seats: 5, brand: 'Toyota' })
|
||||
})
|
||||
|
||||
it('parseQuery validates query values and throws ZodError for invalid input', () => {
|
||||
const schema = z.object({ page: z.coerce.number().int().positive() })
|
||||
const req = { query: { page: '0' } } as unknown as Request
|
||||
|
||||
expect(() => parseQuery(schema, req)).toThrow('Number must be greater than 0')
|
||||
})
|
||||
|
||||
it('parseParams returns validated path parameters', () => {
|
||||
const schema = z.object({ vehicleId: z.string().min(1) })
|
||||
const req = { params: { vehicleId: 'veh_123' } } as unknown as Request
|
||||
|
||||
expect(parseParams(schema, req)).toEqual({ vehicleId: 'veh_123' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Request } from 'express'
|
||||
import { ValidationError } from './errors'
|
||||
|
||||
export function getRawBodyString(req: Request) {
|
||||
if (!Buffer.isBuffer(req.body)) {
|
||||
throw new ValidationError('Webhook route must be mounted with express.raw before JSON parsing')
|
||||
}
|
||||
return req.body.toString('utf8')
|
||||
}
|
||||
|
||||
export function parseRawJsonBody<T = unknown>(req: Request): T {
|
||||
const rawBody = getRawBodyString(req)
|
||||
try {
|
||||
return JSON.parse(rawBody) as T
|
||||
} catch {
|
||||
throw new ValidationError('Malformed webhook JSON')
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user