import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox' import { UserSchema } from '../plugins/schemas/auth.ts' import { GetUserQuerySchema, UpdateUserPayloadSchema, UpdateUserPreferencesPayloadSchema, UserPreferencesSchema } from '../plugins/schemas/user.ts' import { TypeboxRef } from '../utils/typebox-ref.ts' const plugin: FastifyPluginAsyncTypebox = async (fastify) => { fastify.get( '/user', { schema: { summary: 'Get user', tags: ['User'], operationId: 'user.get', querystring: TypeboxRef(GetUserQuerySchema), response: { 200: TypeboxRef(UserSchema), }, }, }, async (req, reply) => { const user = await fastify.prisma.user.findFirst({ where: { username: req.query.username }, select: { username: true, displayName: true, createdAt: true, }, }) if (!user) { return reply.notFound('User not found') } return { ...user, createdAt: user.createdAt.toISOString(), } }, ) fastify.get( '/user/preferences', { schema: { summary: 'Get preferences', tags: ['User'], operationId: 'user.getPreferences', response: { 200: TypeboxRef(UserPreferencesSchema), }, }, }, async (req) => { const user = req.user! const preferences = await fastify.prisma.userPreferences.upsert({ where: { username: user.username }, create: { username: user.username }, update: {}, }) return { toggleInputHotkey: preferences.toggleInputHotkey || '', toggleOutputHotkey: preferences.toggleOutputHotkey || '', } }, ) fastify.patch( '/user/preferences', { schema: { summary: 'Update preferences', tags: ['User'], operationId: 'user.updatePreferences', body: TypeboxRef(UpdateUserPreferencesPayloadSchema), }, }, async (req) => { const user = req.user! return fastify.prisma.userPreferences.upsert({ where: { username: user.username }, create: { username: user.username, ...req.body, }, update: req.body, }) }, ) fastify.patch( '/profile', { schema: { summary: 'Update profile', tags: ['User'], operationId: 'user.updateProfile', body: TypeboxRef(UpdateUserPayloadSchema), response: { 200: TypeboxRef(UserSchema), }, }, }, async (req, reply) => { const user = req.user! const updatedUser = await fastify.prisma.user.update({ where: { username: user.username }, data: { displayName: req.body.displayName, }, select: { username: true, displayName: true, createdAt: true, }, }) if (!updatedUser) { return reply.notFound('User not found') } const response = { ...updatedUser, createdAt: updatedUser.createdAt.toISOString(), } fastify.bus.emit('user:profile-updated', response) // TODO: подписаться в webrtc // const namespace: Namespace = fastify.io.of('/webrtc') // const sockets = await namespace.fetchSockets() // // const found = sockets.find(socket => socket.data.joined && socket.data.userId === req.user!.id) // // if (found) { // found.data.displayName = req.body.displayName // namespace.emit('clientChanged', found.id, socketToClient(found)) // } return response }, ) } export default plugin