Skip to content

Commit

Permalink
fix: naming refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
danny-mv committed Feb 12, 2024
1 parent f99b84f commit 5cc555a
Show file tree
Hide file tree
Showing 87 changed files with 515 additions and 376 deletions.
7 changes: 6 additions & 1 deletion back/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@

All notable changes to this project will be documented in this file.

## [0.10.0] - 2024-02-07
## [0.10.0] - 2024-02-12

### Added

- `attachUserNamesToResources` to unify and simplify resource object structure across the application by ensuring all resources include `user` details (name and optionally `avatarId`) and `favorites`
-`markFavorites` to mark resources as favorites based on user interaction,
- Get users name by id from SSO endpoint

### Changed

- Endpoint naming conventions in SSOhandler have been updated to align with the latest changes in the SSO. This update affects several endpoints and query string handling. For a complete list of endpoint naming changes and their implications, please refer to the [SSO changelog](../sso/CHANGELOG.md#190---2024-02-07).
- Removed unnecessary nesting in the Prisma query within the `getFavoriteResources` middleware.
- Adjusted middleware sequence: errorMiddleware now initialized before koaBody to capture body parsing errors.
- User name is now handled by SSO.
Expand All @@ -24,6 +26,9 @@ All notable changes to this project will be documented in this file.
- Organized MSW handlers into separate files
- Added to ssoServer mock, get users name by id handler.

### Documentation

- Added `UpstreamServiceFail` response

## [0.9.0] - 2024-01-24

Expand Down
14 changes: 14 additions & 0 deletions back/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ components:
example: User not found
required:
- message
UpstreamServiceFail:
type: object
properties:
message:
type: string
example: Upstream service failed to respond with the required data
required:
- message
ServiceUnavailableError:
type: object
properties:
Expand Down Expand Up @@ -2067,6 +2075,12 @@ paths:
example: Database error
required:
- message
"502":
description: Upstream service fail
content:
application/json:
schema:
$ref: "#/components/schemas/UpstreamServiceFail"
/api/v1/favorites:
put:
tags:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import supertest from 'supertest'
import { expect, it, describe } from 'vitest'
import { server } from '../globalSetup'
import { pathRoot } from '../../routes/routes'
import { itineraryGetSchema } from '../../schemas/itinerary/itineraryGetSchema'
import { ssoServer } from '../mocks/ssoServer'
import { itinerariesListSchema } from '../../schemas/itinerary/itinerariesListSchema'

describe('Testing category GET method', () => {
it('Should respond OK status and return itineraries as an array. As per seed data, it should not be empty, and contain objects with an id and category name.', async () => {
Expand All @@ -12,7 +12,7 @@ describe('Testing category GET method', () => {
expect(response.status).toBe(200)
expect(response.body).toBeInstanceOf(Array)
expect(response.body.length).toBeGreaterThan(0)
expect(() => itineraryGetSchema.parse(response.body)).not.toThrow()
expect(() => itinerariesListSchema.parse(response.body)).not.toThrow()
expect(response.body).toEqual(
expect.arrayContaining([
expect.objectContaining({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { http, HttpResponse } from 'msw'
import { testUserData } from '../../globalSetup'
import { authToken } from './authToken'

type GetUserResponse =
type GetMeUsersResponse =
| { message: string }
| { dni: string; email: string; role: string; status: string }
export const getUserHandler = http.post(
'http://localhost:8000/api/v1/user',
export const getMeUsersHandler = http.post(
'http://localhost:8000/api/v1/users/me',
async ({ request }) => {
const { authToken: token } = (await request.json()) as {
authToken: string
Expand All @@ -16,7 +16,7 @@ export const getUserHandler = http.post(
return HttpResponse.json(
{
message: 'Invalid Credentials',
} as GetUserResponse,
} as GetMeUsersResponse,
{ status: 401 }
)
}
Expand All @@ -27,7 +27,7 @@ export const getUserHandler = http.post(
return HttpResponse.json(
{
message: 'Invalid Credentials',
} as GetUserResponse,
} as GetMeUsersResponse,
{ status: 401 }
)
}
Expand All @@ -40,7 +40,7 @@ export const getUserHandler = http.post(
name,
role,
status,
} as GetUserResponse,
} as GetMeUsersResponse,
{ status: 200 }
)
}
Expand Down
8 changes: 4 additions & 4 deletions back/src/__tests__/mocks/ssoHandlers/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { loginHandler } from './loginHandler'
export { registerHandler, mockRegisterId } from './registerHandler'
export { validateTokenHandler } from './validateTokenHandler'
export { getUserHandler } from './getUserHandler'
export { patchUserHandler } from './patchUserHandler'
export { getUsersNameByIdHandler } from './getUsersNameByIdHandler'
export { getItinerariesHandler } from './getItinerariesHandler'
export { getMeUsersHandler as getUserHandler } from './getMeUsersHandler'
export { updateUserHandler } from './updateUserHandler'
export { listUsersHandler as getUsersNameByIdHandler } from './listUsersHandler'
export { listItinerariesHandler } from './listItinerariesHandler'
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { HttpResponse, http } from 'msw'

export const getItinerariesHandler = http.get(
'http://localhost:8000/api/v1/itinerary',
export const listItinerariesHandler = http.get(
'http://localhost:8000/api/v1/itineraries',
async () => {
const itineraries = [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@ import { http, HttpResponse } from 'msw'
import QueryString from 'qs'
import { testUserData } from '../../globalSetup'

export const getUsersNameByIdHandler = http.get<
export const listUsersHandler = http.get<
never,
{ message: string } | { id: string; name: string }[]
>('http://localhost:8000/api/v1/users/name', async ({ request }) => {
>('http://localhost:8000/api/v1/users', async ({ request }) => {
const url = new URL(request.url)
const queryString = url.search.slice(1)
const decodeQuery = decodeURIComponent(queryString)
const userIds = QueryString.parse(decodeQuery, { comma: true }) as {
const queryParse = QueryString.parse(decodeQuery, { comma: true }) as {
id: string[]
fields: string[]
}
if (typeof userIds.id === 'string') userIds.id = [userIds.id]
if (!userIds.id) return HttpResponse.json([], { status: 200 })
const uniqueIds = [...new Set(userIds.id)]
if (typeof queryParse.id === 'string') queryParse.id = [queryParse.id]
if (!queryParse.id) return HttpResponse.json([], { status: 200 })
const uniqueIds = [...new Set(queryParse.id)]
const findUsers = uniqueIds
.map((id) => Object.values(testUserData).find((user) => user.id === id))
.filter(Boolean)
Expand Down
33 changes: 0 additions & 33 deletions back/src/__tests__/mocks/ssoHandlers/patchUserHandler.ts

This file was deleted.

56 changes: 56 additions & 0 deletions back/src/__tests__/mocks/ssoHandlers/updateUserHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { http, HttpResponse } from 'msw'
import { TSsoPatchUserRequest } from '../../../schemas/sso'
import { authToken } from './authToken'
import { testUserData } from '../../globalSetup'
import { UserRole, UserStatus } from '../../../schemas/users/userSchema'

type UpdateUserResponse = { message: string }
export const updateUserHandler = http.patch(
'http://localhost:8000/api/v1/users/:id',
async ({ request, params }) => {
const sampleUser = {
id: 'jvrbkpeq9v6l4l23rt0u00w9',
email: '[email protected]',
name: 'sampleUser',
dni: '00000000R',
password: 'testingPswd1',
role: UserRole.REGISTERED,
status: UserStatus.ACTIVE,
avatarId: null,
}
const updatedUserData = { ...testUserData, sampleUser }
const { id } = params
const { authToken: token } = (await request.json()) as TSsoPatchUserRequest
const isValidToken = Object.values(authToken).includes(token)
if (!isValidToken) {
return HttpResponse.json(
{
message: 'Invalid Credentials',
} as UpdateUserResponse,
{ status: 401 }
)
}
const user = Object.values(updatedUserData).find((u) => u.id === id)
if (!user) {
return HttpResponse.json(
{
message: 'User not found',
},
{ status: 404 }
)
}
const userType = Object.keys(authToken).find(
(key) => authToken[key] === token
)
if (!userType) {
return HttpResponse.json(
{
message: 'Invalid Credentials',
} as UpdateUserResponse,
{ status: 401 }
)
}

return new HttpResponse(null, { status: 204 })
}
)
8 changes: 4 additions & 4 deletions back/src/__tests__/mocks/ssoServer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { setupServer } from 'msw/node'
import {
getItinerariesHandler,
listItinerariesHandler,
getUserHandler,
getUsersNameByIdHandler,
loginHandler,
patchUserHandler,
updateUserHandler,
registerHandler,
validateTokenHandler,
} from './ssoHandlers'
Expand All @@ -14,9 +14,9 @@ const handlers = [
registerHandler,
validateTokenHandler,
getUserHandler,
patchUserHandler,
updateUserHandler,
getUsersNameByIdHandler,
getItinerariesHandler,
listItinerariesHandler,
]

export const ssoServer = setupServer(...handlers)
17 changes: 17 additions & 0 deletions back/src/__tests__/users/patchUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,23 @@ describe('Testing user patch endpoint', () => {

expect(response.status).toBe(204)
})
it('should fail if the user ID does not exist in SSO', async () => {
const modifiedUser = {
id: 'xsgjgke8sae1973kqotrept4',
name: 'UpdatedSampleUser',
status: UserStatus.INACTIVE,
}
expect(userPatchSchema.safeParse(modifiedUser).success).toBeTruthy()
const response = await supertest(server)
.patch(`${pathRoot.v1.users}`)
.set('Cookie', [`authToken=${authToken.admin}`])
.send(modifiedUser)

expect(response.status).toBe(502)
expect(response.body.message).toBe(
'Upstream service failed to respond with the required data'
)
})
it('User patch should fail if attempted with invalid data', async () => {
const modifiedUser = {
id: sampleUser!.id,
Expand Down
2 changes: 1 addition & 1 deletion back/src/controllers/auth/authMeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { ssoHandler } from '../../helpers'
export const authMeController: Middleware = async (ctx: Context) => {
const { id } = ctx.user
const authToken = ctx.cookies.get('authToken') as string
const data = await ssoHandler.getUser({ authToken })
const data = await ssoHandler.getMeUsers({ authToken })
const user = await prisma.user.findUnique({
where: { id },
select: {
Expand Down
2 changes: 1 addition & 1 deletion back/src/controllers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ export { patchUser } from './users/patch'
export { patchResource } from './resources/patchResource'
export { putFavoriteByUserId } from './favorites/putFavoriteByUserId'
export { createSeenResource } from './seen/create'
export { getItineraries } from './itinerary/get'
export { listItineraries } from './itineraries/list'
8 changes: 8 additions & 0 deletions back/src/controllers/itineraries/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import Koa, { Middleware } from 'koa'
import { ssoHandler } from '../../helpers'

export const listItineraries: Middleware = async (ctx: Koa.Context) => {
const data = await ssoHandler.listItineraries()
ctx.status = 200
ctx.body = data
}
8 changes: 0 additions & 8 deletions back/src/controllers/itinerary/get.ts

This file was deleted.

2 changes: 1 addition & 1 deletion back/src/controllers/users/patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { UserPatchSchema } from '../../schemas/users/userPatchSchema'
export const patchUser: Middleware = async (ctx: Context) => {
const { id, ...newData } = ctx.request.body as UserPatchSchema
const authToken = ctx.cookies.get('authToken') as string
await ssoHandler.patchUser({ id, authToken, ...newData })
await ssoHandler.updateUser({ id, authToken, ...newData })
const media = ctx.file
let newMediaId: string
if (media) {
Expand Down
2 changes: 1 addition & 1 deletion back/src/helpers/attachUserNamesToResources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type UnifiedResources =
| ExtendedResourceWithFavorites[]
| ExtendedResourceWithAvatar[]
export async function attachUserNamesToResources(resources: UnifiedResources) {
const names = await ssoHandler.getUsersNameById(
const names = await ssoHandler.listUsers(
resources.map((resource) => resource.userId)
)
return resources.map((resource) => {
Expand Down
16 changes: 0 additions & 16 deletions back/src/helpers/sso/getItineraries.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import {
} from '../errors'
import { pathSso } from './pathSso'

export async function getUser(data: TSsoGetUserRequest) {
const fetchSSO = await fetch(pathSso.user, {
export async function getMeUsers(data: TSsoGetUserRequest) {
const fetchSSO = await fetch(pathSso.v1.users.me, {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify(data),
Expand Down
8 changes: 4 additions & 4 deletions back/src/helpers/sso/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export { getItineraries } from './getItineraries'
export { getUser } from './getUser'
export { listItineraries } from './listItineraries'
export { getMeUsers } from './getMeUsers'
export { login } from './login'
export { pathSso } from './pathSso'
export { register } from './register'
export { validate } from './validate'
export { patchUser } from './patchUser'
export { getUsersNameById } from './getUsersNameById'
export { updateUser } from './updateUser'
export { listUsers } from './listUsers'
Loading

0 comments on commit 5cc555a

Please sign in to comment.