-
Notifications
You must be signed in to change notification settings - Fork 390
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
Criar endpoint e componente de atividades do usuário por data #1612
Closed
marlonangeli
wants to merge
3
commits into
filipedeschamps:main
from
marlonangeli:user-activity-table
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
b54dbed
feat(user activity): add `getUserActivity` to `user` model
marlonangeli 8bfae1b
feat(user activity): add `/api/v1/users/[username]/activity` endpoint
marlonangeli a41d212
test(user activity): add tests for `/api/v1/users/[username]/activity…
marlonangeli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -433,6 +433,50 @@ async function updateRewardedAt(userId, options) { | |
return results.rows[0]; | ||
} | ||
|
||
async function getUserActivity(userId) { | ||
if (!userId) { | ||
throw new ValidationError({ | ||
message: `É necessário informar o "id" do usuário.`, | ||
stack: new Error().stack, | ||
errorLocationCode: 'MODEL:USER:GET_USER_ACTIVITY:USER_ID_REQUIRED', | ||
key: 'userId', | ||
}); | ||
} | ||
|
||
const query = { | ||
text: ` | ||
SELECT | ||
COUNT(*)::int as count, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Precisa desse cast aqui? |
||
published_at::date as date | ||
FROM | ||
contents | ||
WHERE | ||
owner_id = $1 AND | ||
status = 'published' AND | ||
created_at IS NOT NULL AND | ||
published_at IS NOT NULL | ||
GROUP BY | ||
owner_id, published_at::date | ||
ORDER BY | ||
date | ||
;`, | ||
values: [userId], | ||
}; | ||
|
||
const results = await database.query(query); | ||
|
||
const response = { | ||
userId: userId, | ||
activity: results.rows, | ||
}; | ||
|
||
for (const activity of response.activity) { | ||
activity.date = activity.date.toISOString().split('T')[0]; | ||
} | ||
|
||
return response; | ||
} | ||
|
||
export default Object.freeze({ | ||
create, | ||
findAll, | ||
|
@@ -444,4 +488,5 @@ export default Object.freeze({ | |
addFeatures, | ||
createAnonymous, | ||
updateRewardedAt, | ||
getUserActivity, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import nextConnect from 'next-connect'; | ||
|
||
import authorization from 'models/authorization'; | ||
import cacheControl from 'models/cache-control'; | ||
import controller from 'models/controller.js'; | ||
import user from 'models/user.js'; | ||
import validator from 'models/validator.js'; | ||
|
||
export default nextConnect({ | ||
attachParams: true, | ||
onNoMatch: controller.onNoMatchHandler, | ||
onError: controller.onErrorHandler, | ||
}) | ||
.use(controller.injectRequestMetadata) | ||
.use(controller.logRequest) | ||
.use(cacheControl.swrMaxAge(10)) | ||
.get(getValidationHandler, getHandler); | ||
|
||
function getValidationHandler(request, response, next) { | ||
const cleanValues = validator(request.query, { | ||
username: 'required', | ||
}); | ||
|
||
request.query = cleanValues; | ||
|
||
next(); | ||
} | ||
|
||
async function getHandler(request, response) { | ||
const userTryingToGet = user.createAnonymous(); | ||
const userDataFromDatabase = await user.findOneByUsername(request.query.username, { | ||
withBalance: false, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Não precisa passar |
||
}); | ||
|
||
if (!userDataFromDatabase) { | ||
return response.status(404).json({ | ||
message: `O usuário informado não foi encontrado no sistema.`, | ||
action: 'Verifique se o "username" está digitado corretamente.', | ||
stack: new Error().stack, | ||
errorLocationCode: 'CONTROLLER:USER:GET_HANDLER:USERNAME_NOT_FOUND', | ||
key: 'username', | ||
}); | ||
} | ||
|
||
const userActivityFromDatabase = await user.getUserActivity(userDataFromDatabase.id); | ||
|
||
const secureOutputValues = authorization.filterOutput(userTryingToGet, 'read:user', userActivityFromDatabase); | ||
|
||
return response.status(200).json(secureOutputValues); | ||
} |
96 changes: 96 additions & 0 deletions
96
tests/integration/api/v1/users/[username]/activity/get.test.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,96 @@ | ||
import fetch from 'cross-fetch'; | ||
import { version as uuidVersion } from 'uuid'; | ||
|
||
import orchestrator from 'tests/orchestrator.js'; | ||
|
||
beforeAll(async () => { | ||
await orchestrator.waitForAllServices(); | ||
await orchestrator.dropAllTables(); | ||
await orchestrator.runPendingMigrations(); | ||
}); | ||
|
||
describe('GET /api/v1/users/[username]/activity', () => { | ||
describe('Anonymous user', () => { | ||
test('Retrieving non-existing user', async () => { | ||
const response = await fetch(`${orchestrator.webserverUrl}/api/v1/users/donotexist/activity`, { | ||
method: 'GET', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
}); | ||
|
||
const responseBody = await response.json(); | ||
|
||
expect(response.status).toEqual(404); | ||
expect(responseBody.status_code).toEqual(404); | ||
expect(responseBody.name).toEqual('NotFoundError'); | ||
expect(responseBody.message).toEqual('O "username" informado não foi encontrado no sistema.'); | ||
expect(responseBody.action).toEqual('Verifique se o "username" está digitado corretamente.'); | ||
expect(responseBody.status_code).toEqual(404); | ||
expect(responseBody.error_location_code).toEqual('MODEL:USER:FIND_ONE_BY_USERNAME:NOT_FOUND'); | ||
expect(uuidVersion(responseBody.error_id)).toEqual(4); | ||
expect(uuidVersion(responseBody.request_id)).toEqual(4); | ||
expect(responseBody.key).toEqual('username'); | ||
}); | ||
|
||
test('Retrieving nuked user', async () => { | ||
const userCreated = await orchestrator.createUser({ username: 'nukedUser' }); | ||
|
||
await orchestrator.addFeaturesToUser(userCreated, ['nuked']); | ||
|
||
const response = await fetch(`${orchestrator.webserverUrl}/api/v1/users/nukedUser/activity`); | ||
|
||
const responseBody = await response.json(); | ||
|
||
expect(response.status).toEqual(404); | ||
expect(responseBody.status_code).toEqual(404); | ||
expect(responseBody.name).toEqual('NotFoundError'); | ||
expect(responseBody.message).toEqual('O "username" informado não foi encontrado no sistema.'); | ||
expect(responseBody.action).toEqual('Verifique se o "username" está digitado corretamente.'); | ||
expect(responseBody.status_code).toEqual(404); | ||
expect(responseBody.error_location_code).toEqual('MODEL:USER:FIND_ONE_BY_USERNAME:NOT_FOUND'); | ||
expect(uuidVersion(responseBody.error_id)).toEqual(4); | ||
expect(uuidVersion(responseBody.request_id)).toEqual(4); | ||
expect(responseBody.key).toEqual('username'); | ||
}); | ||
|
||
test('Retrieving user with no activity', async () => { | ||
const userCreated = await orchestrator.createUser({ username: 'userWithNoActivity' }); | ||
|
||
const response = await fetch(`${orchestrator.webserverUrl}/api/v1/users/userWithNoActivity/activity`); | ||
|
||
const responseBody = await response.json(); | ||
|
||
expect(response.status).toEqual(200); | ||
expect(responseBody).toEqual({ | ||
id: userCreated.id, | ||
activity: [], | ||
}); | ||
}); | ||
|
||
test('Retrieving user with activity', async () => { | ||
const userCreated = await orchestrator.createUser({ username: 'userWithActivity' }); | ||
|
||
await orchestrator.createContent({ | ||
owner_id: userCreated.id, | ||
title: 'contentCreated', | ||
status: 'published', | ||
}); | ||
|
||
const response = await fetch(`${orchestrator.webserverUrl}/api/v1/users/userWithActivity/activity`); | ||
|
||
const responseBody = await response.json(); | ||
|
||
expect(response.status).toEqual(200); | ||
expect(responseBody).toEqual({ | ||
id: userCreated.id, | ||
activity: [ | ||
{ | ||
count: 1, | ||
date: new Date().toISOString().split('T')[0], | ||
}, | ||
], | ||
}); | ||
}); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Não sei se essa é a melhor forma de definir o
filteredOutputValues
, mas de todo modo, sugiro utilizar chaves{
e}
noif
e noelse
para facilitar a identificação dos blocos.