Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: init backend server #1

Merged
merged 1 commit into from
Feb 2, 2024
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
104 changes: 100 additions & 4 deletions package-lock.json

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

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
"license": "ISC",
"dependencies": {
"@prisma/client": "^5.9.1",
"@types/jsonwebtoken": "^9.0.5",
"dotenv": "^16.4.1",
"fastify": "^4.26.0",
"fastify-plugin": "^4.5.1",
"fastify-schema-to-ts": "^1.0.1"
"fastify-schema-to-ts": "^1.0.1",
"jsonwebtoken": "^9.0.2"
},
"devDependencies": {
"@types/node": "^20.11.16",
Expand Down
65 changes: 65 additions & 0 deletions src/DTO/index.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import ErrorConfig from '@errors/config';
import { ErrorWithToast } from '@errors';
export const AuthorizationHeader = {
type: 'object',
properties: {
authorization: { type: 'string' },
},
required: ['authorization'],
} as const;

export const StoreAuthorizationHeader = {
type: 'object',
properties: {
authorization: { type: 'string' },
storeid: { type: 'string' },
},
required: ['authorization', 'storeid'],
} as const;

export const errorSchema = (...errors: Array<new (message:string,...any:any) => ErrorWithToast>) => {
const errorConfigs = ErrorConfig.filter((errorConfig) => errors.some((error) => errorConfig.error === error));
return errorConfigs.reduce((acc, cur) => {
const errorInstance = new cur.error("");
if(acc[cur.code]) {
acc[cur.code].properties.error.enum.push(errorInstance.name);
acc[cur.code].description += `\n${cur.describtion}`;
acc[cur.code].properties.toast.enum.push(cur.toast(errorInstance));
return acc;
}
acc[cur.code] = {
type: 'object',
description: cur.describtion,
required: ['error','message','toast'],
properties: {
error: { type: 'string', enum: [errorInstance.name] },
message: { type: 'string'},
toast: { type: 'string', enum: [cur.toast(errorInstance)] }
}
}
return acc;
},{} as {
[key:number]: {
type: 'object',
description: string,
required: ['error','message','toast'],
properties: {
error: { type: 'string', enum: string[] },
message: { type: 'string'},
toast: { type: 'string', enum: string[] }
}
}
});
};

export type ErrorInterface = FromSchema<{
type: 'object',
description: string,
required: ['error','message','toast'],
properties: {
error: { type: 'string', enum: string[] },
message: { type: 'string'},
toast: { type: 'string', enum: string[] }
}
}>;
20 changes: 20 additions & 0 deletions src/api/hooks/checkUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { LoginToken } from '@utils/jwt';
import { FastifyRequest, FastifyReply, FastifyError } from 'fastify';
import { UserAuthorizationError, NoAuthorizationInHeaderError } from '@errors/index';

export default async (
request: FastifyRequest<{ Body: { userId: number } }>,
reply: FastifyReply,
done: (err?: FastifyError) => void
) => {
const authorization = request.headers.authorization;
if (!authorization) {
throw new NoAuthorizationInHeaderError('헤더에 Authorization이 없습니다');
}

const replace_authorization = authorization.replace('Bearer ', '');

if(!request.body)
request.body = { userId: 0 };
request.body.userId = LoginToken.getUserId(replace_authorization);
};
39 changes: 39 additions & 0 deletions src/api/hooks/onError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { FastifyRequest, FastifyReply, FastifyError } from 'fastify';
import { ErrorWithToast, ValidationError } from '@errors';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
import ErrorConfig from '@errors/config';

export default (
request: FastifyRequest,
reply: FastifyReply,
error: FastifyError & { toast?: string }
) => {
if (!(error instanceof ErrorWithToast)) {
if (error.validation) {
error.toast = ErrorConfig.find(
(config) => config.error === ValidationError
)!.toast(error);
return reply.code(400).send(error);
}
if(error as FastifyError & { toast?: string } instanceof PrismaClientKnownRequestError) {
if(error.code === 'P2025') {
error.toast = '찾을 수 없는 데이터가 포함되어 있습니다.';
return reply.code(404).send(error);
}
error.toast = '잘못된 데이터가 입력되었습니다.';
return reply.code(400).send(error);
}
error.toast = '알 수 없는 에러가 발생했습니다.';
return reply.code(500).send(error);
}
const knownError = ErrorConfig.find(
(config) => error instanceof config.error
);
if (knownError) {
return reply
.code(knownError.code)
.send(error.setToast(knownError.toast(error)));
}

reply.code(500).send();
};
8 changes: 8 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { FastifyInstance, FastifyPluginAsync, FastifySchema } from 'fastify';
import test from './routes/apiTest';

const api: FastifyPluginAsync = async (server: FastifyInstance) => {
server.register(test, { prefix: '/' });
};

export default api;
26 changes: 26 additions & 0 deletions src/api/routes/apiTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { FastifyInstance, FastifyPluginAsync, FastifySchema } from 'fastify';
import onError from '@hooks/onError';
import { NotDefinedOnConfigError } from '@errors/index';

const test: FastifyPluginAsync = async (server: FastifyInstance) => {
const testSchema: FastifySchema = {
response: {
200: {
type: 'object',
properties: {
data: { type: 'string' },
},
},
},
};
server.get('/ping', { schema: testSchema }, async (req, rep) => {
return { data: 'pong' };
});
server.post('/notDefinedOnConfigerror', { onError }, async (req, rep) => {
throw new NotDefinedOnConfigError('notDefinedOnConfigerror');
});
server.post('/notDefinederror', { onError }, async (req, rep) => {
throw new Error('notDefinederror');
});
};
export default test;
27 changes: 27 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { config } from 'dotenv';

class Config{
static instance: Config|null=null;
constructor() {}

static of(): Config {
if (!Config.instance) {
config();
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
Config.instance = new Config();
}
return Config.instance;
}

config() {
return {
port: parseInt(process.env.NODE_ENV == 'test' ? '3001' : process.env.PORT || '3000'),
jwtSecretKey: process.env.JWT_SECRET_KEY || 'secretKey',
salt: process.env.SALT || 'salt',
nodeEnv: process.env.NODE_ENV,
} as const;
}

}

export default Config.of().config();
Loading