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

Criar endpoint e componente de atividades do usuário por data #1612

Closed
Closed
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
26 changes: 16 additions & 10 deletions models/authorization.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,16 +176,22 @@ function filterOutput(user, feature, output) {
}

if (feature === 'read:user') {
filteredOutputValues = {
id: output.id,
username: output.username,
description: output.description,
features: output.features,
tabcoins: output.tabcoins,
tabcash: output.tabcash,
created_at: output.created_at,
updated_at: output.updated_at,
};
if (output.activity)
Copy link
Collaborator

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 } no if e no else para facilitar a identificação dos blocos.

filteredOutputValues = {
id: output.userId,
activity: output.activity,
};
else
filteredOutputValues = {
id: output.id,
username: output.username,
description: output.description,
features: output.features,
tabcoins: output.tabcoins,
tabcash: output.tabcash,
created_at: output.created_at,
updated_at: output.updated_at,
};
}

if (feature === 'read:user:self') {
Expand Down
45 changes: 45 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Copy link
Collaborator

Choose a reason for hiding this comment

The 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,
Expand All @@ -444,4 +488,5 @@ export default Object.freeze({
addFeatures,
createAnonymous,
updateRewardedAt,
getUserActivity,
});
50 changes: 50 additions & 0 deletions pages/api/v1/users/[username]/activity/index.public.js
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,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não precisa passar withBalance: false porque já é o padrão.

});

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 tests/integration/api/v1/users/[username]/activity/get.test.js
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],
},
],
});
});
});
});