add user config routes

This commit is contained in:
2025-07-24 12:17:30 +05:30
parent 05abf66d66
commit ee31f3ae20
7 changed files with 119 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { getConfig, updateConfig } from "./userConfig.service";
import { UpdateUserConfigInput } from "./userConfig.schema";
export async function getConfigHandler(req: FastifyRequest, res: FastifyReply) {
try {
const config = await getConfig(req.user);
return res.code(200).send(config);
} catch (err) {
return err;
}
}
export async function updateConfigHandler(
req: FastifyRequest,
res: FastifyReply
) {
const input = req.body as UpdateUserConfigInput;
console.log(input);
try {
const updatedConfig = await updateConfig(input, req.user);
return res.code(200).send(updatedConfig);
} catch (err) {
return err;
}
}

View File

@@ -0,0 +1,26 @@
import { FastifyInstance } from "fastify";
import { getConfigHandler, updateConfigHandler } from "./userConfig.controller";
import { $userConfig } from "./userConfig.schema";
export async function userConfigRoutes(fastify: FastifyInstance) {
fastify.get(
"/",
{
config: { requiredClaims: ["config:read"] },
preHandler: [fastify.authorize],
},
getConfigHandler
);
fastify.patch(
"/",
{
schema: {
body: $userConfig("updateUserConfigInput"),
},
config: { requiredClaims: ["config:write"] },
preHandler: [fastify.authorize],
},
updateConfigHandler
);
}

View File

@@ -0,0 +1,30 @@
import { buildJsonSchemas } from "fastify-zod";
import mongoose from "mongoose";
import { z } from "zod";
export const userConfigModel = mongoose.model(
"userConfig",
new mongoose.Schema({
tenantId: String,
userId: {
type: mongoose.Types.ObjectId,
unique: true,
},
config: Object,
}),
"userConfig"
);
const updateUserConfigInput = z.object({
config: z.record(z.string(), z.any()).optional(),
});
export type UpdateUserConfigInput = z.infer<typeof updateUserConfigInput>;
export const { schemas: userConfigSchemas, $ref: $userConfig } =
buildJsonSchemas(
{
updateUserConfigInput,
},
{ $id: "userConfig" }
);

View File

@@ -0,0 +1,30 @@
import { AuthenticatedUser } from "../auth";
import { UpdateUserConfigInput, userConfigModel } from "./userConfig.schema";
export async function createUserConfig(userId: string, tenantId: string) {
await userConfigModel.create({ tenantId, userId, config: {} });
}
export async function getConfig(user: AuthenticatedUser) {
return await userConfigModel.findOne({
tenantId: user.tenantId,
userId: user.userId,
});
}
export async function updateConfig(
input: UpdateUserConfigInput,
user: AuthenticatedUser
) {
return await userConfigModel.findOneAndUpdate(
{ tenantId: user.tenantId, userId: user.userId },
{
...input,
},
{ new: true }
);
}
export async function deleteConfig(userId: string, tenantId: string) {
await userConfigModel.deleteOne({ userId: userId, tenantId: tenantId });
}