Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controller and test migrated to knex methods #1569

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 22 additions & 21 deletions services/wiki/src/__tests__/resources/post.test.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,48 @@
import supertest from 'supertest'
import { expect, test, describe, beforeAll, afterAll } from 'vitest'
import { expect, describe, beforeAll, afterAll, test } from 'vitest'
import cuid from 'cuid'
import { server, testCategoryData } from '../globalSetup'
import { prisma } from '../../prisma/client'
import { pathRoot } from '../../routes/routes'
import { checkInvalidToken } from '../helpers/checkInvalidToken'
import { authToken } from '../mocks/ssoHandlers/authToken'
import db from '../../db/knex'
import { KnexResource } from '../../db/knexTypes'

let topicIds: string[] = []

beforeAll(async () => {
topicIds = (await prisma.topic.findMany()).map((topic) => topic.id)
topicIds = (await db('topic').select('id')).map((topic) => topic.id)
})

afterAll(async () => {
await prisma.topicsOnResources.deleteMany({
where: { resource: { slug: 'test-resource' } },
})
await prisma.resource.deleteMany({
where: { slug: 'test-resource' },
})
await db('topic_resource')
// eslint-disable-next-line func-names
.whereIn('resource_id', function () {
this.select('id').from('resource').where({ slug: 'test-resource' })
})
.del()
await db('resource').where({ slug: 'test-resource' }).del()
})

describe('Testing resource creation endpoint', async () => {
const category = await prisma.category.findUnique({
where: { slug: testCategoryData.slug },
})
const category = await db('category')
.where({ slug: testCategoryData.slug })
.first()

const newResource = {
id: cuid(),
title: 'Test Resource',
description: 'This is a new resource',
url: 'https://example.com/resource',
resourceType: 'BLOG',
resource_type: KnexResource.BLOG,
category_id: category?.id,
topics: topicIds,
categoryId: category?.id,
}
test('should create a new resource with topics', async () => {
newResource.topics = topicIds
const response = await supertest(server)
.post(`${pathRoot.v1.resources}`)
.set('Cookie', [`authToken=${authToken.admin}`])
.send(newResource)

expect(response.status).toBe(204)
})

Expand All @@ -50,25 +52,24 @@ describe('Testing resource creation endpoint', async () => {
.post(`${pathRoot.v1.resources}`)
.set('Cookie', [`authToken=${authToken.admin}`])
.send(newResource)

expect(response.status).toBe(422)
})

test('should fail with wrong resource type', async () => {
const id2 = cuid()
const invalidResource = {
id: id2,
title: 'Invalid Resource',
description: 'This is a new resource',
url: 'https://example.com/resource',
resourceType: 'INVALIDE-RESOURCE',
topicId: topicIds,
status: 'NOT_SEEN',
resource_type: 'INVALIDE-RESOURCE',
topics: topicIds,
}

const response = await supertest(server)
.post(`${pathRoot.v1.resources}`)
.set('Cookie', [`authToken=${authToken.admin}`])
.send(invalidResource)

expect(response.status).toBe(400)
expect(response.body.message[0].received).toBe('INVALIDE-RESOURCE')
})
Expand Down
2 changes: 1 addition & 1 deletion services/wiki/src/controllers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export { loginController } from './auth/loginController'
export { logoutController } from './auth/logoutController'
export { registerController } from './auth/register'
export { authMeController } from './auth/authMeController'
export { postResource } from './resources/postResource'
export { postResource } from './resources/post'
export { listResources } from './resources/list'
export { getResourcesById } from './resources/getResourcesById'
export { getResourcesByUserId } from './resources/getResourcesByUserId'
Expand Down
36 changes: 36 additions & 0 deletions services/wiki/src/controllers/resources/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import Koa, { Middleware } from 'koa'
import slugify from 'slugify'
import { MissingParamError } from '../../helpers/errors'
import db from '../../db/knex'
import { User } from '../../db/knexTypes'
import { createResourceTopics } from '../../helpers/wiki/createResourceTopics'

export const postResource: Middleware = async (ctx: Koa.Context) => {
const { id: userId } = ctx.user as User
// eslint-disable-next-line @typescript-eslint/naming-convention
const { category_id, topics, ...rest } = ctx.request.body

const resource = rest

const slug = slugify(resource.title, { lower: true })

if (topics.length === 0) throw new MissingParamError('topics')

const resourceTopics = await db('topic').whereIn(
'id',
topics.map((id: any) => id)
)

await db('resource').insert({
...resource,
user_id: userId,
slug,
created_at: new Date(),
updated_at: new Date(),
category_id,
})

await createResourceTopics(resource?.id, resourceTopics)

ctx.status = 204
}
43 changes: 0 additions & 43 deletions services/wiki/src/controllers/resources/postResource.ts

This file was deleted.

15 changes: 15 additions & 0 deletions services/wiki/src/helpers/wiki/createResourceTopics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import db from '../../db/knex'
import { Topic } from '../../db/knexTypes'

export const createResourceTopics = async (
resourceId: string,
topicIds: Topic[]
) => {
const resourceTopics = topicIds.map((topicId) => ({
resource_id: resourceId,
topic_id: topicId.id,
created_at: new Date(),
}))

await db('topic_resource').insert(resourceTopics)
}
5 changes: 3 additions & 2 deletions services/wiki/src/routes/resourcesRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ import {
getFavoriteResources,
postResource,
} from '../controllers'
import { resourceCreateSchema, resourcesListParamsSchema } from '../schemas'
import { resourcesListParamsSchema } from '../schemas'
import { pathRoot } from './routes'
import { patchResource } from '../controllers/resources/patchResource'
import { resourcePatchSchema } from '../schemas/resource/resourcePatchSchema'
import { knexResourceCreateSchema } from '../schemas/resource/resourceCreateSchema'

const resourcesRouter = new Router()

Expand All @@ -20,7 +21,7 @@ resourcesRouter.prefix(pathRoot.v1.resources)
resourcesRouter.post(
'/',
authenticate,
validate(z.object({ body: resourceCreateSchema })),
validate(z.object({ body: knexResourceCreateSchema })),
postResource
)

Expand Down
Loading