Skip to content
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
5 changes: 5 additions & 0 deletions .changeset/fifty-pens-hammer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/service-errors': patch
---

Report HTTP method in `RouteNotFound` error
5 changes: 5 additions & 0 deletions .changeset/sharp-bees-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/service-core': patch
---

Make 404 error body consistent with other error responses.
4 changes: 3 additions & 1 deletion packages/service-core/src/routes/configure-fastify.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type fastify from 'fastify';
import * as uuid from 'uuid';

import { registerFastifyRoutes } from './route-register.js';
import { registerFastifyNotFoundHandler, registerFastifyRoutes } from './route-register.js';

import * as system from '../system/system-index.js';

Expand Down Expand Up @@ -76,6 +76,8 @@ export function configureFastifyServer(server: fastify.FastifyInstance, options:
*/
server.register(async function (childContext) {
registerFastifyRoutes(childContext, generateContext, routes.api?.routes ?? DEFAULT_ROUTE_OPTIONS.api.routes);
registerFastifyNotFoundHandler(childContext);

// Limit the active concurrent requests
childContext.addHook(
'onRequest',
Expand Down
56 changes: 41 additions & 15 deletions packages/service-core/src/routes/route-register.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import type fastify from 'fastify';
import * as uuid from 'uuid';

import { errors, HTTPMethod, logger, router } from '@powersync/lib-services-framework';
import {
ErrorCode,
errors,
HTTPMethod,
logger,
RouteNotFound,
router,
ServiceError
} from '@powersync/lib-services-framework';
import { Context, ContextProvider, RequestEndpoint, RequestEndpointHandlerPayload } from './router.js';
import { FastifyReply } from 'fastify';

export type FastifyEndpoint<I, O, C> = RequestEndpoint<I, O, C> & {
parse?: boolean;
Expand Down Expand Up @@ -69,23 +78,11 @@ export function registerFastifyRoutes(
const serviceError = errors.asServiceError(ex);
requestLogger.error(`Request failed`, serviceError);

response = new router.RouterResponse({
status: serviceError.errorData.status || 500,
headers: {
'Content-Type': 'application/json'
},
data: {
error: serviceError.errorData
}
});
response = serviceErrorToResponse(serviceError);
}

Object.keys(response.headers).forEach((key) => {
reply.header(key, response.headers[key]);
});
reply.status(response.status);
try {
await reply.send(response.data);
await respond(reply, response);
} finally {
await response.afterSend?.({ clientClosed: request.socket.closed });
requestLogger.info(`${e.method} ${request.url}`, {
Expand All @@ -106,3 +103,32 @@ export function registerFastifyRoutes(
});
}
}

/**
* Registers a custom not-found handler to ensure 404 error responses have the same schema as other service errors.
*/
export function registerFastifyNotFoundHandler(app: fastify.FastifyInstance) {
app.setNotFoundHandler(async (request, reply) => {
await respond(reply, serviceErrorToResponse(new RouteNotFound(request.originalUrl, request.method)));
});
}

function serviceErrorToResponse(error: ServiceError): router.RouterResponse {
return new router.RouterResponse({
status: error.errorData.status || 500,
headers: {
'Content-Type': 'application/json'
},
data: {
error: error.errorData
}
});
}

async function respond(reply: FastifyReply, response: router.RouterResponse) {
Object.keys(response.headers).forEach((key) => {
reply.header(key, response.headers[key]);
});
reply.status(response.status);
await reply.send(response.data);
}
9 changes: 7 additions & 2 deletions packages/service-errors/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,17 @@ export class InternalServerError extends ServiceError {
export class RouteNotFound extends ServiceError {
static readonly CODE = ErrorCode.PSYNC_S2002;

constructor(path: string) {
constructor(path: string, method?: string) {
let pathDescription = JSON.stringify(path);
if (method != null) {
pathDescription = `${method} ${pathDescription}`;
}

super({
code: RouteNotFound.CODE,
status: 404,
description: 'The path does not exist on this server',
details: `The path ${JSON.stringify(path)} does not exist on this server`,
details: `The path ${pathDescription} does not exist on this server`,
severity: ErrorSeverity.INFO
});
}
Expand Down