diff --git a/services/wiki/src/__tests__/resources/me.test.ts b/services/wiki/src/__tests__/resources/me.test.ts index d3313876..5e86465d 100644 --- a/services/wiki/src/__tests__/resources/me.test.ts +++ b/services/wiki/src/__tests__/resources/me.test.ts @@ -13,16 +13,20 @@ let user: User | null let userWithNoName: User | null beforeAll(async () => { + // Buscar categoria por slug const testCategory = (await prisma.category.findUnique({ where: { slug: testCategoryData.slug }, })) as Category + // Busco usuario user = await prisma.user.findFirst({ where: { id: testUserData.user.id }, }) + // busco usuario sin nombre userWithNoName = await prisma.user.findFirst({ where: { id: testUserData.userWithNoName.id }, }) + // recursos con user const testResourcesWithUser = resourceTestData.map((resource) => { return { ...resource, @@ -31,6 +35,7 @@ beforeAll(async () => { } }) + // creo recurso sin user const resourceTest4: Omit< Prisma.ResourceCreateArgs['data'], 'userId' | 'categoryId' @@ -48,23 +53,27 @@ beforeAll(async () => { categoryId: testCategory.id, } + // junto los 4 recursos testResourcesWithUser.push(testResourcesWithNoUserName) + // creo 4 recursos await prisma.resource.createMany({ data: testResourcesWithUser, }) + // busco un recurso por slug const testResource = await prisma.resource.findUnique({ where: { slug: resourceTestData[0].slug }, }) + // creo favorito entre recurso y usuario await prisma.favorites.create({ data: { resourceId: testResource!.id, userId: user!.id, }, }) - + // agrego un voto al recurso donde coincide usuario y recurso await prisma.vote.upsert({ where: { userId_resourceId: { @@ -84,18 +93,21 @@ beforeAll(async () => { }) afterAll(async () => { + // borro favoritos del usuario await prisma.favorites.deleteMany({ where: { user: { id: user?.id } }, }) - + // borro favoritos del usuario sin nombre await prisma.favorites.deleteMany({ where: { user: { id: userWithNoName?.id } }, }) + // borro votos y recursos del usuario await prisma.vote.deleteMany({}) await prisma.resource.deleteMany({ where: { user: { id: user?.id } }, }) + // borro recursos sin usuario await prisma.resource.deleteMany({ where: { user: { id: userWithNoName?.id } }, }) @@ -135,12 +147,14 @@ describe('Testing resources/me endpoint', () => { }) }) - it('Given a valid category slug, should return resources related to that category', async () => { - const testCategorySlug = 'testing' + it.only('Given a valid category slug, should return resources related to that category', async () => { + const categorySlug = testCategoryData.slug const response = await supertest(server) .get(`${pathRoot.v1.resources}/me`) .set('Cookie', [`authToken=${authToken.user}`]) - .query({ testCategorySlug }) + .query({ categorySlug }) + console.log('response body', response.body) + expect(response.status).toBe(200) expect(response.body).toBeInstanceOf(Array) expect(response.body.length).toBeGreaterThanOrEqual(1) diff --git a/services/wiki/src/controllers/resources/getResourcesByUserId.ts b/services/wiki/src/controllers/resources/getResourcesByUserId.ts index 514eda20..9bdb5e76 100644 --- a/services/wiki/src/controllers/resources/getResourcesByUserId.ts +++ b/services/wiki/src/controllers/resources/getResourcesByUserId.ts @@ -1,6 +1,6 @@ import { User } from '@prisma/client' import Koa, { Middleware } from 'koa' -import { prisma } from '../../prisma/client' +// import { prisma } from '../../prisma/client' import { resourceGetSchema } from '../../schemas' import { attachUserNamesToResources, @@ -8,48 +8,74 @@ import { transformResourceToAPI, } from '../../helpers' import { ExtendedFavoriteResourceWithName } from '../../helpers/markFavorites' +import db from '../../db/knex' export const getResourcesByUserId: Middleware = async (ctx: Koa.Context) => { const user = ctx.user as User const categorySlug = ctx.query.categorySlug as string | undefined - let resources = [] - const include = { - vote: { select: { vote: true, userId: true } }, - topics: { select: { topic: true } }, - favorites: { - where: { userId: user ? user.id : undefined }, - }, - } + const query = db('resource') + .where('resource.user_id', user.id) + .leftJoin('topic_resource', 'topic_resource.resource_id', 'resource.id') + .leftJoin('topic', 'topic.id', 'topic_resource.topic_id') + .leftJoin('vote', 'vote.resource_id', 'resource.id') + .leftJoin('favorites', 'favorites.resource_id', 'resource.id') + .select( + 'resource.*', + db.raw('json_agg(favorites) as favorites'), + db.raw('json_agg(vote) as votes'), + db.raw('json_agg(topic) as topics') + ) + .groupBy('resource.id') + // normalmente entraba aqui, porque categorySlug era undefined if (!categorySlug) { - resources = await prisma.resource.findMany({ - where: { userId: user.id }, - include, - }) + // find resources by user id + // resources = await prisma.resource.findMany({ + // where: { userId: user.id }, + // include, + // }) + resources = await query } else { - const topicsInCategory = await prisma.topic.findMany({ - where: { - category: { - slug: categorySlug, - }, - }, - }) - resources = await prisma.resource.findMany({ - where: { - user: { id: { equals: user.id } }, - topics: { - some: { - topicId: { - in: topicsInCategory.map(({ id }) => id), - }, - }, - }, - }, - include, - }) + // find topics by slug and find resources by topics + + // const topicsInCategory = await prisma.topic.findMany({ + // where: { + // category: { + // slug: categorySlug, + // }, + // }, + // }) + // resources = await prisma.resource.findMany({ + // where: { + // user: { id: { equals: user.id } }, + // topics: { + // some: { + // topicId: { + // in: topicsInCategory.map(({ id }) => id), + // }, + // }, + // }, + // }, + // include, + // }) + const categoryId = await db('category') + .where({ slug: categorySlug }) + .first('id') + + const topicsInCategoryKnex = await db('topic') + .where({ category_id: categoryId }) + .returning('id') + + query.whereIn( + 'topic_resource.topic_id', + topicsInCategoryKnex.map(({ id }) => id) + ) + + resources = await query } + console.log('resources', resources) if (resources.length === 0) { ctx.status = 200 @@ -73,3 +99,43 @@ export const getResourcesByUserId: Middleware = async (ctx: Koa.Context) => { ctx.status = 200 ctx.body = parsedResources } + +/* +FORMATO de response PRISMA: [ + { + id: 'cm38hl95d0000vp8k423fjs4b', + title: 'test-resource-1-blog', + slug: 'test-resource-1-blog', + description: 'Lorem ipsum blog', + url: 'https://sample.com', + resourceType: 'BLOG', + categoryId: 'cm38hfu7f0000vp342ru05hl7', + createdAt: '2024-11-08T08:40:31.633Z', + updatedAt: '2024-11-08T08:40:31.633Z', + user: { name: 'testingUser', id: 'vwt15uwddul2afme75x6fs8q' }, + topics: [], + voteCount: { upvote: 1, downvote: 0, total: 1, userVote: 1 }, isFavorite: true + }, +] +*/ + +/* +FORMATO DE resources dentro del if [ + { + id: 'cm3eup1070000vpwg7kxuz6kv', + title: 'test-resource-1-blog', + slug: 'test-resource-1-blog', + description: 'Lorem ipsum blog', + url: 'https://sample.com', + resourceType: 'BLOG', + userId: 'vwt15uwddul2afme75x6fs8q', + categoryId: 'cm3etqo4d0000vpe0u6o5f4mv', + createdAt: 2024-11-12T19:33:59.767Z, + updatedAt: 2024-11-12T19:33:59.767Z, + vote: [ [Object] ], + topics: [], + favorites: [ [Object] ] + }, + +] +*/