feat(services): add POST /channels/[channelId]/messages

This commit is contained in:
Divlo
2022-01-01 01:35:56 +00:00
parent 0003c91f69
commit 766c9fdbd6
12 changed files with 1233 additions and 628 deletions

View File

@ -4,7 +4,7 @@ import { FastifyPluginAsync, FastifySchema } from 'fastify'
import prisma from '../../../tools/database/prisma.js'
import { fastifyErrors } from '../../../models/utils.js'
import authenticateUser from '../../../tools/plugins/authenticateUser.js'
import { channelSchema } from '../../../models/Channel'
import { channelSchema } from '../../../models/Channel.js'
const parametersSchema = Type.Object({
channelId: channelSchema.id

View File

@ -0,0 +1,94 @@
import { application } from '../../../../../application.js'
import { authenticateUserTest } from '../../../../../__test__/utils/authenticateUserTest.js'
import { prismaMock } from '../../../../../__test__/setup.js'
import { channelExample } from '../../../../../models/Channel.js'
import { memberExample } from '../../../../../models/Member.js'
import { userExample } from '../../../../../models/User.js'
import { messageExample } from '../../../../../models/Message.js'
describe('POST /channels/[channelId]/messages', () => {
it('succeeds', async () => {
prismaMock.channel.findUnique.mockResolvedValue(channelExample)
prismaMock.member.findFirst.mockResolvedValue({
...memberExample,
user: userExample
} as any)
prismaMock.message.create.mockResolvedValue(messageExample)
const { accessToken } = await authenticateUserTest()
const response = await application.inject({
method: 'POST',
url: `/channels/${channelExample.id}/messages`,
headers: {
authorization: `Bearer ${accessToken}`
},
payload: {
value: messageExample.value
}
})
const responseJson = response.json()
expect(response.statusCode).toEqual(201)
expect(responseJson.id).toEqual(messageExample.id)
expect(responseJson.value).toEqual(messageExample.value)
expect(responseJson.type).toEqual(messageExample.type)
expect(responseJson.mimetype).toEqual(messageExample.mimetype)
expect(responseJson.member.id).toEqual(memberExample.id)
expect(responseJson.member.isOwner).toEqual(memberExample.isOwner)
expect(responseJson.member.user.id).toEqual(userExample.id)
expect(responseJson.member.user.name).toEqual(userExample.name)
})
it('fails with no message value', async () => {
prismaMock.channel.findUnique.mockResolvedValue(channelExample)
prismaMock.member.findFirst.mockResolvedValue({
...memberExample,
user: userExample
} as any)
const { accessToken } = await authenticateUserTest()
const response = await application.inject({
method: 'POST',
url: `/channels/${channelExample.id}/messages`,
headers: {
authorization: `Bearer ${accessToken}`
},
payload: {}
})
expect(response.statusCode).toEqual(400)
})
it('fails with not found channel', async () => {
prismaMock.channel.findUnique.mockResolvedValue(null)
const { accessToken } = await authenticateUserTest()
const response = await application.inject({
method: 'POST',
url: '/channels/5/messages',
headers: {
authorization: `Bearer ${accessToken}`
},
payload: {
value: messageExample.value
}
})
const responseJson = response.json()
expect(response.statusCode).toEqual(404)
expect(responseJson.message).toEqual('Channel not found')
})
it('fails with not found member', async () => {
prismaMock.channel.findUnique.mockResolvedValue(channelExample)
prismaMock.member.findUnique.mockResolvedValue(null)
const { accessToken } = await authenticateUserTest()
const response = await application.inject({
method: 'POST',
url: `/channels/${channelExample.id}/messages`,
headers: {
authorization: `Bearer ${accessToken}`
},
payload: {
value: messageExample.value
}
})
const responseJson = response.json()
expect(response.statusCode).toEqual(404)
expect(responseJson.message).toEqual('Channel not found')
})
})

View File

@ -0,0 +1,116 @@
import { Static, Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify'
import prisma from '../../../../tools/database/prisma.js'
import { fastifyErrors } from '../../../../models/utils.js'
import authenticateUser from '../../../../tools/plugins/authenticateUser.js'
import { messageSchema } from '../../../../models/Message.js'
import { channelSchema } from '../../../../models/Channel.js'
import { memberSchema } from '../../../../models/Member.js'
import { userPublicWithoutSettingsSchema } from '../../../../models/User.js'
const parametersSchema = Type.Object({
channelId: channelSchema.id
})
type Parameters = Static<typeof parametersSchema>
const bodyPostServiceSchema = Type.Object({
value: messageSchema.value
})
type BodyPostServiceSchemaType = Static<typeof bodyPostServiceSchema>
const postServiceSchema: FastifySchema = {
description: 'POST a new message in a specific channel using its channelId.',
tags: ['messages'] as string[],
security: [
{
bearerAuth: []
}
] as Array<{ [key: string]: [] }>,
body: bodyPostServiceSchema,
params: parametersSchema,
response: {
200: Type.Object({
...messageSchema,
member: Type.Object({
...memberSchema,
user: Type.Object(userPublicWithoutSettingsSchema)
})
}),
400: fastifyErrors[400],
401: fastifyErrors[401],
403: fastifyErrors[403],
404: fastifyErrors[404],
500: fastifyErrors[500]
}
} as const
export const postMessageByChannelIdService: FastifyPluginAsync = async (
fastify
) => {
await fastify.register(authenticateUser)
fastify.route<{
Body: BodyPostServiceSchemaType
Params: Parameters
}>({
method: 'POST',
url: '/channels/:channelId/messages',
schema: postServiceSchema,
handler: async (request, reply) => {
if (request.user == null) {
throw fastify.httpErrors.forbidden()
}
const { channelId } = request.params
const channel = await prisma.channel.findUnique({
where: { id: channelId }
})
if (channel == null) {
throw fastify.httpErrors.notFound('Channel not found')
}
const memberCheck = await prisma.member.findFirst({
where: { guildId: channel.guildId, userId: request.user.current.id },
include: {
user: {
select: {
id: true,
name: true,
logo: true,
status: true,
biography: true,
website: true,
createdAt: true,
updatedAt: true
}
}
}
})
if (memberCheck == null) {
throw fastify.httpErrors.notFound('Channel not found')
}
const { value } = request.body
const message = await prisma.message.create({
data: {
value,
type: 'text',
mimetype: 'text/plain',
channelId,
memberId: memberCheck.id
}
})
reply.statusCode = 201
return {
...message,
member: {
...memberCheck,
user: {
...memberCheck.user,
email: null
}
}
}
}
})
}

View File

@ -1,9 +1,11 @@
import { FastifyPluginAsync } from 'fastify'
import { getChannelByIdService } from './[channelId]/get'
import { getMessagesByChannelIdService } from './[channelId]/messages/get'
import { getChannelByIdService } from './[channelId]/get.js'
import { getMessagesByChannelIdService } from './[channelId]/messages/get.js'
import { postMessageByChannelIdService } from './[channelId]/messages/post.js'
export const channelsService: FastifyPluginAsync = async (fastify) => {
await fastify.register(getChannelByIdService)
await fastify.register(getMessagesByChannelIdService)
await fastify.register(postMessageByChannelIdService)
}

View File

@ -4,7 +4,7 @@ import { FastifyPluginAsync, FastifySchema } from 'fastify'
import prisma from '../../../../tools/database/prisma.js'
import { fastifyErrors } from '../../../../models/utils.js'
import authenticateUser from '../../../../tools/plugins/authenticateUser.js'
import { guildSchema } from '../../../../models/Guild'
import { guildSchema } from '../../../../models/Guild.js'
import { channelSchema } from '../../../../models/Channel.js'
import {
getPaginationOptions,

View File

@ -5,11 +5,11 @@ import { FastifyPluginAsync, FastifySchema } from 'fastify'
import prisma from '../../../tools/database/prisma.js'
import { fastifyErrors } from '../../../models/utils.js'
import authenticateUser from '../../../tools/plugins/authenticateUser.js'
import { guildSchema } from '../../../models/Guild'
import { guildSchema } from '../../../models/Guild.js'
import {
getPaginationOptions,
queryPaginationSchema
} from '../../../tools/database/pagination'
} from '../../../tools/database/pagination.js'
const querySchema = Type.Object({
search: Type.Optional(Type.String()),