Skip to content

Commit

Permalink
feat: handle error with customAssert
Browse files Browse the repository at this point in the history
  • Loading branch information
solufa committed Jul 16, 2024
1 parent e47790d commit c48a0c6
Show file tree
Hide file tree
Showing 10 changed files with 42 additions and 14 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
"generate:client": "npm run generate --prefix client",
"generate:server": "npm run generate --prefix server",
"lint": "run-p lint:*",
"lint:client": "npm run lint:fix --prefix client",
"lint:server": "npm run lint:fix --prefix server",
"lint:client": "npm run lint --prefix client",
"lint:server": "npm run lint --prefix server",
"start": "run-p start:*",
"start:client": "npm start --prefix client",
"start:server": "npm start --prefix server",
Expand Down
15 changes: 13 additions & 2 deletions server/api/health/controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import { CustomError } from 'service/customAssert';
import { prismaClient } from 'service/prismaClient';
import { s3 } from 'service/s3Client';
import { defineController } from './$relay';

const throwCustomError = (label: string) => (e: Error) => {
/* v8 ignore next 2 */
throw new CustomError(`${label} ${e.message}`);
};

export default defineController(() => ({
get: async () => ({
status: 200,
body: {
server: 'ok',
db: await prismaClient.$queryRaw`SELECT CURRENT_TIMESTAMP;`.then(() => 'ok' as const),
storage: await s3.health().then(() => 'ok' as const),
db: await prismaClient.$queryRaw`SELECT CURRENT_TIMESTAMP;`
.then(() => 'ok' as const)
.catch(throwCustomError('DB')),
s3: await s3
.health()
.then(() => 'ok' as const)
.catch(throwCustomError('S3')),
},
}),
}));
2 changes: 1 addition & 1 deletion server/api/health/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import type { DefineMethods } from 'aspida';

export type Methods = DefineMethods<{
get: {
resBody: Record<'server' | 'db' | 'storage', 'ok'>;
resBody: Record<'server' | 'db' | 's3', 'ok'>;
};
}>;
4 changes: 2 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"predev": "run-p generate migrate:deploy",
"dev": "run-p dev:*",
"dev:build": "node ./scripts/build.dev.js",
"dev:server": "touch index.js && node-dev --respawn index.js",
"dev:server": "touch index.js && node-dev --enable-source-maps --respawn index.js",
"dev:frourio": "frourio --watch",
"dev:prisma": "prisma generate --watch",
"prebuild": "run-p generate migrate:deploy",
Expand All @@ -27,7 +27,7 @@
"typecheck": "tsc --noEmit"
},
"prisma": {
"seed": "node -r esbuild-register prisma/seed.ts"
"seed": "node -r esbuild-register --enable-source-maps prisma/seed.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.569.0",
Expand Down
9 changes: 5 additions & 4 deletions server/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { prismaClient } from 'service/prismaClient';
import type { Prisma } from '@prisma/client';
import { prismaClient, transaction } from 'service/prismaClient';

async function main(): Promise<void> {
const someFn = async (_tx: Prisma.TransactionClient): Promise<void> => {
// seeder script
}
};

main()
transaction('RepeatableRead', (tx) => Promise.all([someFn(tx)]))
.catch((e) => {
console.error(e);
process.exit(1);
Expand Down
1 change: 0 additions & 1 deletion server/scripts/build.prod.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@ const config = require('./config.common');
build({
...config,
minify: true,
sourcemap: 'linked',
define: { 'process.env.NODE_ENV': `"production"`, 'import.meta.vitest': 'false' },
}).catch(() => process.exit(1));
1 change: 1 addition & 0 deletions server/scripts/config.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ module.exports = {
bundle: true,
plugins: [nodeExternalsPlugin()],
logLevel: 'info',
sourcemap: 'linked',
};
11 changes: 10 additions & 1 deletion server/service/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import Fastify from 'fastify';
import buildGetJwks from 'get-jwks';
import server from '../$server';
import { COOKIE_NAME } from './constants';
import { CustomError } from './customAssert';
import {
API_BASE_PATH,
COGNITO_POOL_ENDPOINT,
Expand Down Expand Up @@ -60,10 +61,18 @@ export const init = (): FastifyInstance => {
await req
.jwtVerify<JwtUser>({ onlyCookie: true })
.then((user) => websocket.add(user.sub, socket))
.catch((e) => socket.close(401, e.message));
.catch(() => null);
});
});

fastify.setErrorHandler((err, req, reply) => {
console.error(new Date(), err.stack);

reply
.status(req.method === 'GET' ? 404 : 403)
.send(err instanceof CustomError ? err.message : undefined);
});

server(fastify, { basePath: API_BASE_PATH });

return fastify;
Expand Down
7 changes: 7 additions & 0 deletions server/service/customAssert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import assert from 'assert';

export class CustomError extends Error {}

export function customAssert(val: unknown, msg: string): asserts val {
assert(val, new CustomError(msg));
}
2 changes: 1 addition & 1 deletion server/tests/api/public.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ test(GET(noCookieClient.health), async () => {

expect(res.server).toEqual('ok');
expect(res.db).toEqual('ok');
expect(res.storage).toEqual('ok');
expect(res.s3).toEqual('ok');
});

test(POST(noCookieClient.session), async () => {
Expand Down

0 comments on commit c48a0c6

Please sign in to comment.