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

1542 bewiki migrate resources controller tests list to knex methods #1568

Open
wants to merge 4 commits 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
83 changes: 45 additions & 38 deletions services/wiki/src/__tests__/resources/list.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,35 @@
import { expect, it, describe, beforeAll, afterAll } from 'vitest'
import {
Prisma,
Category,
RESOURCE_TYPE,
Resource,
User,
ViewedResource,
// Category,
// RESOURCE_TYPE,
// Resource,
// User,
// ViewedResource,
} from '@prisma/client'
import qs from 'qs'
import { z } from 'zod'
import { server, testCategoryData, testUserData } from '../globalSetup'
import { pathRoot } from '../../routes/routes'
import { prisma } from '../../prisma/client'
import { resourceGetSchema, topicSchema } from '../../schemas'
import { resourceTestData } from '../mocks/resources'
import { resourceGetSchema } from '../../schemas'
import {
knexResourceTestDataUpdated,
resourceTestData,

Check failure on line 19 in services/wiki/src/__tests__/resources/list.test.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

'resourceTestData' is defined but never used

Check failure on line 19 in services/wiki/src/__tests__/resources/list.test.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

'resourceTestData' is defined but never used
} from '../mocks/resources'
import { checkInvalidToken } from '../helpers/checkInvalidToken'
import { authToken } from '../mocks/ssoHandlers/authToken'
import { knexResourceGetSchema } from '../../schemas/resource/resourceGetSchema'
import { knexTopicSchema } from '../../schemas/topic/topicSchema'
import {
KnexResource,
Resource,
ViewedResource,
User,
Category,
} from '../../db/knexTypes'
import db from '../../db/knex'
// import { User } from '../../db/knexTypes'

type ResourceVotes = {
[key: string]: number
Expand All @@ -34,20 +48,19 @@
let userWithNoName: User | null

beforeAll(async () => {
const testCategory = (await prisma.category.findUnique({
where: { slug: testCategoryData.slug },
})) as Category
user = await prisma.user.findFirst({
where: { id: testUserData.user.id },
})
adminUser = await prisma.user.findFirst({
where: { id: testUserData.admin.id },
})
userWithNoName = await prisma.user.findFirst({
where: { id: testUserData.userWithNoName.id },
})
const testCategory = (await db('category')
.where({ slug: testCategoryData.slug })
.first()) as Category

user = await db('user').where({ id: testUserData.user.id }).first()

adminUser = await db('user').where({ id: testUserData.admin.id }).first()

const testResources = resourceTestData.map((testResource) => ({
userWithNoName = await db('user')
.where({ id: testUserData.userWithNoName.id })
.first()

const testResources = knexResourceTestDataUpdated.map((testResource) => ({
...testResource,
user: { connect: { id: user?.id } },
topics: {
Expand Down Expand Up @@ -122,9 +135,9 @@
})
})
// resourceTypes as array from prisma types for the it.each tests.
const resourceTypes = Object.keys(RESOURCE_TYPE)
type ResourceGetSchema = z.infer<typeof resourceGetSchema>
type TopicSchema = z.infer<typeof topicSchema>
const resourceTypes = Object.keys(KnexResource)
type ResourceGetSchema = z.infer<typeof knexResourceGetSchema>
type TopicSchema = z.infer<typeof knexTopicSchema>

describe('Testing resources GET endpoint', () => {
it('should fail with wrong resourceType', async () => {
Expand All @@ -135,7 +148,7 @@
expect(response.status).toBe(400)
})

it('should get all resources by topic id', async () => {
it.only('should get all resources by topic id', async () => {
const existingTopic = await prisma.topic.findUnique({
where: { slug: 'testing' },
})
Expand All @@ -149,9 +162,7 @@
expect(response.body.length).toBeGreaterThanOrEqual(1)
response.body.forEach((resource: ResourceGetSchema) => {
expect(() => resourceGetSchema.parse(resource)).not.toThrow()
expect(
resource.topics.map((t: { topic: TopicSchema }) => t.topic.id)
).toContain(topicId)
expect(resource.topics.map((t: TopicSchema) => t.id)).toContain(topicId)
})
})

Expand All @@ -176,9 +187,9 @@
expect(() => resourceGetSchema.parse(resource)).not.toThrow()
// The returned resource has at least a topic related to the queried category
expect(
resource.topics.some(async (t: { topic: TopicSchema }) => {
resource.topics.some(async (t: TopicSchema) => {
const categoryFromTopic = await prisma.topic.findUnique({
where: { id: t.topic.id },
where: { id: t.id },
include: { category: { select: { slug: true } } },
})
return categoryFromTopic?.category.slug === categorySlug
Expand Down Expand Up @@ -209,15 +220,13 @@
expect(response.body.length).toBeGreaterThanOrEqual(1)
response.body.forEach((resource: ResourceGetSchema) => {
expect(() => resourceGetSchema.parse(resource)).not.toThrow()
expect(
resource.topics.map((t: { topic: TopicSchema }) => t.topic.id)
).toContain(topicId)
expect(resource.resourceType).toBe(resourceType)
expect(resource.topics.map((t: TopicSchema) => t.id)).toContain(topicId)
expect(resource.resource_type).toBe(resourceType)
// The returned resource has at least a topic related to the queried category
expect(
resource.topics.some(async (t: { topic: TopicSchema }) => {
resource.topics.some(async (t: TopicSchema) => {
const categoryFromTopic = await prisma.topic.findUnique({
where: { id: t.topic.id },
where: { id: t.id },
include: { category: { select: { slug: true } } },
})
return categoryFromTopic?.category.slug === categorySlug
Expand All @@ -239,9 +248,7 @@
response.body.forEach((resource: ResourceGetSchema) => {
expect(() => resourceGetSchema.parse(resource)).not.toThrow()
expect(
resource.topics.some(
(topic: { topic: TopicSchema }) => topic.topic.slug === topicSlug
)
resource.topics.some((topic: TopicSchema) => topic.slug === topicSlug)
).toBe(true)
})
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import Koa, { Middleware } from 'koa'
// import { User } from '@prisma/client'
import { NotFoundError } from '../../helpers/errors'
import db from '../../db/knex'
import { attachUserNamesToResources } from '../../helpers/wiki/attachUserNamesToResources'
Expand Down
142 changes: 88 additions & 54 deletions services/wiki/src/controllers/resources/list.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { Prisma, User } from '@prisma/client'
import Koa, { Middleware } from 'koa'
import { prisma } from '../../prisma/client'
import { resourceGetSchema } from '../../schemas'
import { TResourcesListParamsSchema } from '../../schemas/resource/resourcesListParamsSchema'
import db from '../../db/knex'
import { User } from '../../db/knexTypes'
import { attachUserNamesToResourcesKnex } from '../../helpers/attachUserNamesToResources'
import {
attachUserNamesToResources,
markFavorites,
transformResourceToAPI,
ExtendedFavoriteResourceWithName,
} from '../../helpers'
ExtendedFavoriteResourceWithNameKnex,
markFavoritesKnex,
} from '../../helpers/markFavorites'
import { transformResourceToAPIKnex } from '../../helpers/transformResourceToAPI'
import { knexResourceGetSchema } from '../../schemas/resource/resourceGetSchema'

export const listResources: Middleware = async (ctx: Koa.Context) => {
const user = ctx.user as User | null

const {
resourceTypes,
topic: topicId,
Expand All @@ -20,67 +21,100 @@
status,
search,
} = ctx.query as TResourcesListParamsSchema
let statusCondition: Prisma.Enumerable<Prisma.ResourceWhereInput> = {}
if (user && status) {
const viewedFilter = { userId: user.id }
if (status === 'SEEN') {
statusCondition = { AND: { viewed: { some: viewedFilter } } }
} else if (status === 'NOT_SEEN') {
statusCondition = { NOT: { viewed: { some: viewedFilter } } }
}
}
const where: Prisma.ResourceWhereInput = {
topics: {
some: {
topic: {
category: { slug: categorySlug },
id: topicId,
slug: topicSlug,
},
},
},
resourceType: { in: resourceTypes },
...statusCondition,
...(search &&
search.trim().length >= 2 && {
OR: [
{ title: { contains: search, mode: 'insensitive' } },
{ description: { contains: search, mode: 'insensitive' } },
],
}),
}
const voteSelect =
ctx.user !== null ? { userId: true, vote: true } : { vote: true }

const resources = await prisma.resource.findMany({
where,
include: {
vote: { select: voteSelect },
topics: { select: { topic: true } },
favorites: {
where: { userId: user ? user.id : undefined },
},
},
})
const resources = await db('resource')
.leftJoin('topic_resource', 'resource.id', 'topic_resource.resource_id')
.leftJoin('topic', 'topic.id', 'topic_resource.topic_id')
.leftJoin('category', 'category.id', 'topic.category_id')
.leftJoin('vote', 'resource.id', 'vote.resource_id')
.leftJoin('favorites', 'resource.id', 'favorites.resource_id')
.leftJoin('viewed_resource', 'resource.id', 'viewed_resource.resource_id')
.whereExists(function () {

Check warning on line 32 in services/wiki/src/controllers/resources/list.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

Unexpected unnamed function
this.select('*')
.from('topic_resource')
.leftJoin('topic', 'topic.id', 'topic_resource.topic_id') // Necesario para acceder a 'topic.id' y 'topic.slug'
.leftJoin('category', 'category.id', 'topic.category_id') // Necesario para acceder a 'topic.id' y 'topic.slug'
.whereRaw('topic_resource.resource_id = resource.id')
.andWhere(function () {

Check warning on line 38 in services/wiki/src/controllers/resources/list.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

Unexpected unnamed function
if (topicId) {
this.where('topic.id', topicId)
}
if (topicSlug) {
this.orWhere('topic.slug', topicSlug)
}
if (categorySlug) {
this.where('category.slug', categorySlug)
}
})
})
.modify((query) => {
if (user && status) {
if (status === 'SEEN') {
query.where('viewed_resource.user_id', user.id)
}
if (status === 'NOT_SEEN') {
query.whereNot('viewed_resource.user_id', user.id)
}
}
})
.modify((query) => {
if (resourceTypes && resourceTypes.length > 0) {
query.where('resource.resource_type', resourceTypes)
}

if (search && search.trim().length >= 2) {
query.where(function () {

Check warning on line 66 in services/wiki/src/controllers/resources/list.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

Unexpected unnamed function
this.where('resource.title', 'ilike', `%${search}%`).orWhere(
'resource.description',
'ilike',
`%${search}%`
)
})
}
})
.modify((query) => {
if (user !== null) {
query.select(db.raw('json_agg(vote.user_id, vote.vote) AS vote'))
} else {
query.select(db.raw('json_agg(vote.vote) AS vote'))
}
})
.select(
'resource.*',
// db.raw('json_agg(vote.*) AS vote')
db.raw('json_agg(topic.*) AS topics')
// db.raw('json_agg(favorites.*) AS favorites')
)
.modify((query) => {
if (user && user.id) {
query
.where('favorites.user_id', user.id)
.select(db.raw('json_agg(favorites.*) AS favorites'))
} else {
query.select(db.raw('json_build_array() AS favorites'))
}
})
.groupBy('resource.id')

if (resources.length === 0) {
ctx.status = 200
ctx.body = []
return
}

const resourcesWithUserName = await attachUserNamesToResources(resources)
const resourcesWithFavorites = markFavorites(
const resourcesWithUserName = await attachUserNamesToResourcesKnex(resources)

const resourcesWithFavorites = markFavoritesKnex(
resourcesWithUserName.filter(
(resource): resource is ExtendedFavoriteResourceWithName =>
(resource): resource is ExtendedFavoriteResourceWithNameKnex =>
'favorites' in resource
),
user
)

const parsedResources = resourcesWithFavorites.map((resource) =>
resourceGetSchema.parse(
transformResourceToAPI(resource, user ? user.id : undefined)
knexResourceGetSchema.parse(
transformResourceToAPIKnex(resource, user ? user.id : undefined)
)
)

Expand Down
Loading
Loading