diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts index 0eef2dc..a0bd1ba 100644 --- a/src/user/user.controller.ts +++ b/src/user/user.controller.ts @@ -17,6 +17,25 @@ export async function createUserHandler( } } +export async function getCurrentUserHandler( + req: FastifyRequest, + res: FastifyReply +) { + if (req.user.type !== "user") { + return res.code(400).send(); + } + + try { + const user = await getUser(req.user.userId); + if (user == null) + return res.code(404).send({ error: "resource not found" }); + + return res.code(200).send(user); + } catch (err) { + return err; + } +} + export async function getUserHandler(req: FastifyRequest, res: FastifyReply) { const { userId } = req.params as { userId: string }; diff --git a/src/user/user.route.ts b/src/user/user.route.ts index 4de15b1..1e186f1 100644 --- a/src/user/user.route.ts +++ b/src/user/user.route.ts @@ -1,5 +1,9 @@ import { FastifyInstance } from "fastify"; -import { createUserHandler, getUserHandler } from "./user.controller"; +import { + createUserHandler, + getCurrentUserHandler, + getUserHandler, +} from "./user.controller"; import { $user } from "./user.schema"; export default async function userRoutes(fastify: FastifyInstance) { @@ -18,6 +22,18 @@ export default async function userRoutes(fastify: FastifyInstance) { createUserHandler ); + fastify.get( + "/me", + { + schema: { + response: { + 200: $user("createUserResponse"), + }, + }, + }, + getCurrentUserHandler + ); + fastify.get( "/:userId", { diff --git a/src/user/user.service.ts b/src/user/user.service.ts index 1f45559..5df4eaf 100644 --- a/src/user/user.service.ts +++ b/src/user/user.service.ts @@ -1,3 +1,4 @@ +import mongoose from "mongoose"; import { generateId } from "../utils/id"; import { CreateUserInput, UpdateUserInput, userModel } from "./user.schema"; @@ -14,10 +15,13 @@ export async function createUser(input: CreateUserInput, tenantId: string) { } export async function getUser(userId: string) { - const user = await userModel.findOne({ + if (mongoose.Types.ObjectId.isValid(userId)) { + return await userModel.findById(userId); + } + + return await userModel.findOne({ $and: [{ pid: userId }], }); - return user; } export async function getUserByEmail(email: string) {