diff --git a/.env.example b/.env.example index f3142fb..01fe4e4 100644 --- a/.env.example +++ b/.env.example @@ -14,4 +14,4 @@ PORT=3000 BASE_URL_PATH=/api/v1 JWT_SECRET=secret-key -JWT_EXPIRED_IN_MINUTES=100c \ No newline at end of file +JWT_EXPIRED_IN_MINUTES=100 \ No newline at end of file diff --git a/.gitignore b/.gitignore index b752f9d..8fcc382 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,4 @@ node_modules # Keep environment variables out of version control .env -dist \ No newline at end of file +dist/ \ No newline at end of file diff --git a/__tests__/auth.spec.ts b/__tests__/auth.spec.ts index bfd414b..6bcff0f 100644 --- a/__tests__/auth.spec.ts +++ b/__tests__/auth.spec.ts @@ -67,11 +67,11 @@ describe("POST /auth/login", () => { password: AuthTestUtils.user.password, }); - logger.debug(res.body); - expect(res.status).toBe(200); - expect(res.body.data.token).toBeDefined(); + logger.debug(res.body); + expect(res.status).toBe(200); + expect(res.body.data.token).toBeDefined(); - await AuthTestUtils.delete(); + await AuthTestUtils.delete(); }); it("should return 400 - bad request", async () => { @@ -82,9 +82,9 @@ describe("POST /auth/login", () => { password: "", }); - logger.debug(res.body); - expect(res.status).toBe(400); - expect(res.body.errors).toBeDefined(); + logger.debug(res.body); + expect(res.status).toBe(400); + expect(res.body.errors).toBeDefined(); }); it("should return 401 - login failed with wrong credentials", async () => { @@ -95,9 +95,9 @@ describe("POST /auth/login", () => { password: "randompassword", }); - logger.debug(res.body); - expect(res.status).toBe(401); - expect(res.body.errors).toBeDefined(); + logger.debug(res.body); + expect(res.status).toBe(401); + expect(res.body.errors).toBeDefined(); }); }); diff --git a/__tests__/user.spec.ts b/__tests__/user.spec.ts new file mode 100644 index 0000000..d2ccc7f --- /dev/null +++ b/__tests__/user.spec.ts @@ -0,0 +1,68 @@ +import prisma from "../src/application/database"; +import bcrypt from "bcrypt"; +import supertest from "supertest"; +import { basePath, web } from "../src/application/web"; +import logger from "../src/application/logger"; + +describe("GET /user/info", () => { + let token: string = ""; + + beforeAll(async () => { + token = await UserTestUtil.getToken(); + }); + + afterAll(async () => { + await UserTestUtil.delete(); + }); + + it("should return 200 - get user info", async () => { + const res = await supertest(web) + .get(`${basePath}/user/info`) + .set('Authorization', `Bearer ${token}`); + + logger.debug(res.body); + expect(res.status).toBe(200); + expect(res.body.data.username).toBe(UserTestUtil.user.username); + expect(res.body.data.name).toBe(UserTestUtil.user.name); + }); +}); + +class UserTestUtil { + static user = { + name: "user", + username: "user", + password: "password" + }; + + static async create() { + await prisma.user.create({ + data: { + name: UserTestUtil.user.name, + username: UserTestUtil.user.username, + password: await bcrypt.hash(UserTestUtil.user.password, 10), + token: "" + } + }); + } + + static async delete() { + await prisma.user.deleteMany({ + where: { + username: UserTestUtil.user.username + } + }); + } + + static async getToken() { + await UserTestUtil.create(); + + const loginRes = await supertest(web) + .post(`${basePath}/auth/login`) + .send({ + username: UserTestUtil.user.username, + password: UserTestUtil.user.password, + }); + + return loginRes.body.data.token; + } +} \ No newline at end of file diff --git a/dist/application/database.js b/dist/application/database.js deleted file mode 100644 index 8f0a50d..0000000 --- a/dist/application/database.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.prismaClientSingleton = void 0; -const client_1 = require("@prisma/client"); -const logger_1 = __importDefault(require("./logger")); -const prismaClientSingleton = () => { - const prismaClient = new client_1.PrismaClient({ - log: [ - { - emit: "event", - level: "query" - }, - { - emit: "event", - level: "error" - }, - { - emit: "event", - level: "info" - }, - { - emit: "event", - level: "warn" - } - ] - }); - prismaClient.$on("query", (e) => { logger_1.default.info(e); }); - prismaClient.$on("error", (e) => { logger_1.default.error(e); }); - prismaClient.$on("info", (e) => { logger_1.default.info(e); }); - prismaClient.$on("warn", (e) => { logger_1.default.warn(e); }); - return prismaClient; -}; -exports.prismaClientSingleton = prismaClientSingleton; -const prisma = (_a = globalThis.prismaGlobal) !== null && _a !== void 0 ? _a : (0, exports.prismaClientSingleton)(); -exports.default = prisma; diff --git a/dist/application/logger.js b/dist/application/logger.js deleted file mode 100644 index 2d6c1ac..0000000 --- a/dist/application/logger.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.winstonSingleton = void 0; -const winston_1 = __importDefault(require("winston")); -const winstonSingleton = () => winston_1.default.createLogger({ - level: "debug", - format: winston_1.default.format.json(), - transports: [ - new winston_1.default.transports.Console({}) - ] -}); -exports.winstonSingleton = winstonSingleton; -const logger = (_a = globalThis.winstonGlobal) !== null && _a !== void 0 ? _a : (0, exports.winstonSingleton)(); -exports.default = logger; diff --git a/dist/application/web.js b/dist/application/web.js deleted file mode 100644 index 61c34d0..0000000 --- a/dist/application/web.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.web = exports.basePath = void 0; -const express_1 = __importDefault(require("express")); -const auth_1 = require("../router/auth"); -const error_1 = require("../middleware/error"); -const dotenv_1 = __importDefault(require("dotenv")); -const user_1 = require("../router/user"); -dotenv_1.default.config(); -exports.basePath = process.env.BASE_URL_PATH === undefined ? "/api/v1" : process.env.BASE_URL_PATH; -exports.web = (0, express_1.default)(); -exports.web.use(express_1.default.json()); -exports.web.use((0, auth_1.getAuthRouter)(exports.basePath)); -exports.web.use((0, user_1.getUserRouter)(exports.basePath)); -exports.web.use((0, error_1.getErrorMiddleware)()); diff --git a/dist/controller/auth.js b/dist/controller/auth.js deleted file mode 100644 index d0821dc..0000000 --- a/dist/controller/auth.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AuthController = void 0; -const auth_1 = __importDefault(require("../service/auth")); -class AuthController { - static register(req, res, next) { - return __awaiter(this, void 0, void 0, function* () { - try { - const registerReq = req.body; - const registerRes = yield auth_1.default.register(registerReq); - res.status(200) - .json(registerRes); - } - catch (e) { - next(e); - } - }); - } - static login(req, res, next) { - return __awaiter(this, void 0, void 0, function* () { - try { - const loginReq = req.body; - const loginRes = yield auth_1.default.login(loginReq); - res.status(200) - .json({ - data: loginRes - }); - } - catch (e) { - next(e); - } - }); - } -} -exports.AuthController = AuthController; diff --git a/dist/controller/user.js b/dist/controller/user.js deleted file mode 100644 index a671011..0000000 --- a/dist/controller/user.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UserController = void 0; -class UserController { - static info(req, res, next) { - return __awaiter(this, void 0, void 0, function* () { - return res.status(200) - .json({ - data: res.locals.user - }); - }); - } -} -exports.UserController = UserController; diff --git a/dist/error/response.js b/dist/error/response.js deleted file mode 100644 index f37d1f3..0000000 --- a/dist/error/response.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ResponseError = void 0; -class ResponseError extends Error { - constructor(status, message) { - super(message); - this.status = status; - this.message = message; - } -} -exports.ResponseError = ResponseError; diff --git a/dist/main.js b/dist/main.js deleted file mode 100644 index f25cb57..0000000 --- a/dist/main.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const logger_1 = __importDefault(require("./application/logger")); -const web_1 = require("./application/web"); -const dotenv_1 = __importDefault(require("dotenv")); -dotenv_1.default.config(); -const APP_PORT = process.env.PORT; -web_1.web.listen(APP_PORT, () => { logger_1.default.info(`Listening into ${APP_PORT}`); }); diff --git a/dist/middleware/accessValidation.js b/dist/middleware/accessValidation.js deleted file mode 100644 index 49aa48e..0000000 --- a/dist/middleware/accessValidation.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.accessValidation = void 0; -const jwt_1 = __importDefault(require("../service/jwt")); -const accessValidation = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - const { authorization } = req.headers; - if (!authorization) { - return res.status(401).json({ - errors: "empty_authorization" - }); - } - const token = authorization.split(' ')[1]; - try { - const userLocals = yield jwt_1.default.validateJwt(token); - res.locals.user = userLocals; - } - catch (e) { - next(e); - } - next(); -}); -exports.accessValidation = accessValidation; diff --git a/dist/middleware/error.js b/dist/middleware/error.js deleted file mode 100644 index 713d10a..0000000 --- a/dist/middleware/error.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getErrorMiddleware = void 0; -const zod_1 = require("zod"); -const response_1 = require("../error/response"); -const jsonwebtoken_1 = require("jsonwebtoken"); -const getErrorMiddleware = () => (err, req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - if (err instanceof zod_1.ZodError) { - const errItems = {}; - err.issues.forEach((v) => errItems[v.path[0]] = v.message); - res.status(400).json({ - errors: errItems - }); - } - else if (err instanceof response_1.ResponseError) { - res.status(err.status).json({ - errors: err.message - }); - } - else if (err instanceof jsonwebtoken_1.TokenExpiredError) { - return res.status(401).json({ - errors: "expired_authorization" - }); - } - else if (err instanceof jsonwebtoken_1.JsonWebTokenError) { - return res.status(401).json({ - errors: "invalid_token" - }); - } - else { - res.status(500).json({ - errors: "something wrong" - }); - } -}); -exports.getErrorMiddleware = getErrorMiddleware; diff --git a/dist/model/auth.js b/dist/model/auth.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/model/auth.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/model/common.js b/dist/model/common.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/model/common.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/model/user.js b/dist/model/user.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/model/user.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/router/auth.js b/dist/router/auth.js deleted file mode 100644 index 9a03801..0000000 --- a/dist/router/auth.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAuthRouter = void 0; -const express_1 = __importDefault(require("express")); -const auth_1 = require("../controller/auth"); -const getAuthRouter = (basePath) => { - const authRouter = express_1.default.Router(); - authRouter.post(`${basePath}/auth/register`, auth_1.AuthController.register); - authRouter.post(`${basePath}/auth/login`, auth_1.AuthController.login); - return authRouter; -}; -exports.getAuthRouter = getAuthRouter; diff --git a/dist/router/user.js b/dist/router/user.js deleted file mode 100644 index 8152025..0000000 --- a/dist/router/user.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getUserRouter = void 0; -const express_1 = __importDefault(require("express")); -const user_1 = require("../controller/user"); -const accessValidation_1 = require("../middleware/accessValidation"); -const getUserRouter = (basePath) => { - const userRouter = express_1.default.Router(); - userRouter.use(accessValidation_1.accessValidation); - userRouter.get(`${basePath}/user/info`, user_1.UserController.info); - return userRouter; -}; -exports.getUserRouter = getUserRouter; diff --git a/dist/service/auth.js b/dist/service/auth.js deleted file mode 100644 index 4e0126d..0000000 --- a/dist/service/auth.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const database_1 = __importDefault(require("../application/database")); -const response_1 = require("../error/response"); -const auth_1 = require("../validation/auth"); -const validation_1 = require("../validation/validation"); -const bcrypt_1 = __importDefault(require("bcrypt")); -const jwt_1 = __importDefault(require("./jwt")); -class AuthService { - static register(req) { - return __awaiter(this, void 0, void 0, function* () { - const registerReq = validation_1.Validation.validate(auth_1.AuthValidation.REGISTER, req); - const isDuplicateUsername = (yield database_1.default.user.count({ - where: { - username: { - equals: registerReq.username, - mode: 'insensitive' - } - } - })) != 0; - if (isDuplicateUsername) { - throw new response_1.ResponseError(409, "username already exists"); - } - registerReq.username = registerReq.name.toLowerCase(); - registerReq.password = yield bcrypt_1.default.hash(registerReq.password, 10); - const user = yield database_1.default.user.create({ - data: registerReq - }); - return { - status: "success" - }; - }); - } - static login(req) { - return __awaiter(this, void 0, void 0, function* () { - const loginReq = validation_1.Validation.validate(auth_1.AuthValidation.LOGIN, req); - const user = yield database_1.default.user.findUniqueOrThrow({ - where: { - username: loginReq.username.toLowerCase() - } - }).catch(() => { throw new response_1.ResponseError(401, "can't find specified account"); }); - if (!user.password) { - throw new response_1.ResponseError(500, "user password hasn't been set"); - } - const isPasswordValid = yield bcrypt_1.default.compare(loginReq.password, user.password); - if (!isPasswordValid) { - throw new response_1.ResponseError(401, "can't find specified account"); - } - const payload = { - username: user.username, - }; - const token = jwt_1.default.getJwt(payload); - return { token }; - }); - } -} -exports.default = AuthService; diff --git a/dist/service/jwt.js b/dist/service/jwt.js deleted file mode 100644 index d45d52e..0000000 --- a/dist/service/jwt.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const dotenv_1 = __importDefault(require("dotenv")); -const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); -const database_1 = __importDefault(require("../application/database")); -const response_1 = require("../error/response"); -dotenv_1.default.config(); -class JwtService { - static getJwt(payload) { - return jsonwebtoken_1.default.sign(payload, JwtService.jwtSecretKey, { - algorithm: "HS256", - expiresIn: `${JwtService.jwtExpiredInMinutes}m` - }); - } - static validateJwt(token) { - return __awaiter(this, void 0, void 0, function* () { - try { - const jwtDecode = jsonwebtoken_1.default.verify(token, JwtService.jwtSecretKey); - const isUsernameExists = (yield database_1.default.user.count({ - where: { - username: { - equals: jwtDecode.username, - mode: 'insensitive' - } - } - })) != 0; - if (!isUsernameExists) { - throw new response_1.ResponseError(401, "invalid_jwt"); - } - return { - username: jwtDecode.username, - }; - } - catch (e) { - throw e; - } - }); - } -} -JwtService.jwtSecretKey = process.env.JWT_SECRET == undefined ? "secret-key" : process.env.JWT_SECRET; -JwtService.jwtExpiredInMinutes = isNaN(Number(process.env.JWT_EXPIRED_IN_MINUTES)) || Number(process.env.JWT_EXPIRED_IN_MINUTES) < 60 ? 60 : Number(process.env.JWT_EXPIRED_IN_MINUTES); -exports.default = JwtService; diff --git a/dist/service/user.js b/dist/service/user.js deleted file mode 100644 index 4e50d89..0000000 --- a/dist/service/user.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -class UserService { -} -exports.default = UserService; diff --git a/dist/types/jwt.js b/dist/types/jwt.js deleted file mode 100644 index c8ad2e5..0000000 --- a/dist/types/jwt.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/dist/validation/auth.js b/dist/validation/auth.js deleted file mode 100644 index 60674fd..0000000 --- a/dist/validation/auth.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AuthValidation = void 0; -const zod_1 = require("zod"); -class AuthValidation { -} -exports.AuthValidation = AuthValidation; -AuthValidation.REGISTER = zod_1.z.object({ - username: zod_1.z.string({ - invalid_type_error: "username should be string", - required_error: "username is required", - }).min(4, { - message: "username should be more than 4 characters" - }).max(100, { - message: "username should less than 100 characters" - }), - name: zod_1.z.string({ - invalid_type_error: "name should be string", - required_error: "name is required", - }).min(1, { - message: "name should be more than 1 characters" - }).max(100, { - message: "name should less than 100 characters" - }), - password: zod_1.z.string({ - invalid_type_error: "password should be string", - required_error: "password is required", - }).min(6, { - message: "password should be more than 6 characters" - }).max(100, { - message: "password should less than 100 characters" - }), -}); -AuthValidation.LOGIN = zod_1.z.object({ - username: zod_1.z.string({ - invalid_type_error: "username should be string", - required_error: "username is required", - }).min(1, { - message: "username can't be empty" - }), - password: zod_1.z.string({ - invalid_type_error: "password should be string", - required_error: "password is required", - }).min(1, { - message: "password can't be empty" - }) -}); diff --git a/dist/validation/validation.js b/dist/validation/validation.js deleted file mode 100644 index cb25927..0000000 --- a/dist/validation/validation.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Validation = void 0; -class Validation { - static validate(schema, data) { - return schema.parse(data); - } -} -exports.Validation = Validation; diff --git a/src/controller/user.ts b/src/controller/user.ts index efd4811..422cae7 100644 --- a/src/controller/user.ts +++ b/src/controller/user.ts @@ -1,11 +1,18 @@ import { Request, Response, NextFunction } from "express"; +import UserService from "../service/user"; export class UserController { static async info(req: Request, res: Response, next: NextFunction) { - return res.status(200) - .json({ - data: res.locals.user - }) + try { + const infoRes = await UserService.getUserInfo(res.locals.user.username); + + res.status(200) + .json({ + data: infoRes + }); + } catch (e) { + next(e); + } } } \ No newline at end of file diff --git a/src/service/user.ts b/src/service/user.ts index 83b06c8..5b04748 100644 --- a/src/service/user.ts +++ b/src/service/user.ts @@ -1,14 +1,26 @@ import prisma from "../application/database"; +import { ResponseError } from "../error/response"; import { UserInfoResponse } from "../model/user"; export default class UserService { - // static async getUserInfo() : Promise { - // const user = await prisma.user.findFirstOrThrow({ - // where: { - // username: { - // equals: - // } - // } - // }) - // } + static async getUserInfo(username: string) : Promise { + const user = await prisma.user.findFirstOrThrow({ + where: { + username: { + equals: username, + mode: 'insensitive' + } + } + }).catch((e) => { throw new ResponseError(404, "user not found") }); + + console.info({ + username: user.username, + name: user.name + }); + + return { + username: user.username, + name: user.name + } + } } \ No newline at end of file