Skip to content

Commit

Permalink
controller migration - removed client prisma - User type needs to be …
Browse files Browse the repository at this point in the history
…migrated
  • Loading branch information
ghOdisea committed Nov 12, 2024
1 parent dd9ed6e commit 6bb7d78
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 38 deletions.
24 changes: 19 additions & 5 deletions services/wiki/src/__tests__/resources/me.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -31,6 +35,7 @@ beforeAll(async () => {
}
})

// creo recurso sin user
const resourceTest4: Omit<
Prisma.ResourceCreateArgs['data'],
'userId' | 'categoryId'
Expand All @@ -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: {
Expand All @@ -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 } },
})
Expand Down Expand Up @@ -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)

Check warning on line 156 in services/wiki/src/__tests__/resources/me.test.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

Unexpected console statement

expect(response.status).toBe(200)
expect(response.body).toBeInstanceOf(Array)
expect(response.body.length).toBeGreaterThanOrEqual(1)
Expand Down
132 changes: 99 additions & 33 deletions services/wiki/src/controllers/resources/getResourcesByUserId.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,81 @@
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,
markFavorites,
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)

Check warning on line 78 in services/wiki/src/controllers/resources/getResourcesByUserId.ts

View workflow job for this annotation

GitHub Actions / pr_check_service_wiki

Unexpected console statement

if (resources.length === 0) {
ctx.status = 200
Expand All @@ -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] ]
},
]
*/

0 comments on commit 6bb7d78

Please sign in to comment.