diff --git a/src/entry/adaptor/errors.test.ts b/src/entry/adaptor/errors.test.ts new file mode 100644 index 0000000..d91cedf --- /dev/null +++ b/src/entry/adaptor/errors.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; + +describe('正しくエラーコードに変換できる', () => { + const errorToCode = (error: Error) => { + switch (error.message) { + case 'too many members': + return 'TOO_MANY_MEMBERS'; + case 'no member': + return 'NO_MEMBER'; + case 'teamName Exists': + return 'TEAM_ALREADY_EXISTS'; + default: + return 'UNKNOWN_ERROR'; + } + }; + it('too many members', () => { + const error = new Error('too many members'); + expect(errorToCode(error)).toBe('TOO_MANY_MEMBERS'); + }); + it('no member', () => { + const error = new Error('no member'); + expect(errorToCode(error)).toBe('NO_MEMBER'); + }); + it('teamName Exists', () => { + const error = new Error('teamName Exists'); + expect(errorToCode(error)).toBe('TEAM_ALREADY_EXISTS'); + }); + + it('other', () => { + const error = new Error('other'); + expect(errorToCode(error)).toBe('UNKNOWN_ERROR'); + }); +}); diff --git a/src/entry/adaptor/errors.ts b/src/entry/adaptor/errors.ts new file mode 100644 index 0000000..9c29595 --- /dev/null +++ b/src/entry/adaptor/errors.ts @@ -0,0 +1,12 @@ +export function errorToCode(error: Error): string { + switch (error.message) { + case 'too many members': + return 'TOO_MANY_MEMBERS'; + case 'no member': + return 'NO_MEMBER'; + case 'teamName Exists': + return 'TEAM_ALREADY_EXISTS'; + default: + return 'UNKNOWN_ERROR'; + } +} diff --git a/src/entry/main.ts b/src/entry/main.ts index 06e4351..4017c57 100644 --- a/src/entry/main.ts +++ b/src/entry/main.ts @@ -4,6 +4,7 @@ import { entryRequestSchema } from './schema.js'; import { Controller } from './controller.js'; import { Option, Result } from '@mikuroxina/mini-fn'; import { JSONEntryRepository } from './adaptor/json.js'; +import { errorToCode } from './adaptor/errors.js'; export const entryHandler = new Hono(); // export const controller = new Controller(new DummyRepository()); @@ -19,7 +20,7 @@ entryHandler.post('/', zValidator('json', entryRequestSchema), async (c) => { category, }); if (Result.isErr(res)) { - return c.json({ error: res[1].message }, 400); + return c.json({ error: errorToCode(res[1]) }, 400); } return c.json({ @@ -34,7 +35,7 @@ entryHandler.post('/', zValidator('json', entryRequestSchema), async (c) => { entryHandler.get('/', async (c) => { const res = await controller.get(); if (Result.isErr(res)) { - return c.json({ error: res[1].message }, 400); + return c.json({ error: errorToCode(res[1]) }, 400); } return c.json([...res[1]]); diff --git a/tsconfig.json b/tsconfig.json index f19fa69..1f9543f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -19,7 +19,7 @@ "moduleResolution": "Node16", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, - "pretty": true + "pretty": true, }, "include": ["**/*.ts"], "exclude": ["node_modules"]