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

166816218 get all users #32

Merged
Merged
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
23 changes: 23 additions & 0 deletions controllers/users/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,5 +251,28 @@ export default {
return res.status(404).send({
error: 'Notification not Found'
});
},

getUsers: async (req, res) => {
try {
const { query } = req;
const limit = query.limit || 20;
const offset = query.offset ? (query.offset * limit) : 0;

const users = await db.User.findAndCountAll({
offset,
limit,
attributes: ['username', 'firstName', 'lastName', 'image']
});
return res.status(200).json({
users: users.rows,
usersCount: users.count
});
} catch (e) {
return res.status(500).json({
message: 'Something went wrong',
error: e.message,
});
}
}
};
34 changes: 26 additions & 8 deletions db/faker.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const readingTime = require('read-time');
const faker = require('faker');

const getFakeArticle = id => ({
Expand All @@ -7,6 +8,7 @@ const getFakeArticle = id => ({
authorId: id,
createdAt: new Date(),
updatedAt: new Date(),
readTime: readingTime(faker.random.word('string')).text
});

const createFakeArticles = (id) => {
Expand All @@ -19,26 +21,42 @@ const createFakeArticles = (id) => {
};

const getFakeUser = () => ({
email: 'sampoli@gmail.com',
email: faker.internet.email(),
bio: faker.random.word('string'),
firstName: faker.random.words(4),
lastName: faker.random.words(4),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.random.words(4),
password: faker.random.words(10),
image: faker.image.imageUrl(),
role: 'author'
});

const createFakeUser = () => {
const Articles = [];
const getFakeAdmin = () => ({
email: 'admin@haven.com',
bio: faker.random.word('string'),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
username: faker.random.words(4),
password: 'password',
image: faker.image.imageUrl(),
role: 'admin',
});

const createFakeUsers = () => {
const Users = [];
Users.push({ ...getFakeUser(), email: 'sampoli@gmail.com' }, getFakeAdmin());

// eslint-disable-next-line no-plusplus
for (let i = 0; i < 40; i++) {
Articles.push(getFakeUser());
Users.push(getFakeUser());
}
return Articles;
return Users;
};

module.exports = {
getFakeArticle,
createFakeArticles,
getFakeUser,
createFakeUser,
createFakeUsers,
getFakeAdmin
};
4 changes: 2 additions & 2 deletions db/seeders/20190701143128-users.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { getFakeUser } = require('../faker');
const { createFakeUsers } = require('../faker');

module.exports = {
up: async (queryInterface) => {
Expand All @@ -7,7 +7,7 @@ module.exports = {
email: 'sampoli@gmail.com',
},
}, ['email']);
if (!user) queryInterface.bulkInsert('Users', [getFakeUser()], {});
if (!user) queryInterface.bulkInsert('Users', createFakeUsers(), {});
},

down: queryInterface => queryInterface.bulkDelete('Users', null, {})
Expand Down
7 changes: 7 additions & 0 deletions routes/v1/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,12 @@ router.post('/reset-password', Validation.resetPassword, User.resetPassword);
router.put('/change-password', Validation.changePassword, User.changePassword);
router.put('/activate/:token', User.activate);
router.get('/home', User.home);
router.get(
'/',
Middleware.authenticate,
Middleware.isblackListedToken,
Middleware.isAdmin,
User.getUsers
);

export default router;
16 changes: 16 additions & 0 deletions swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,22 @@ paths:
description: User Successfully Updated
'400':
description: Error message
get:
tags:
- Users
summary: Get all users
operationId: getAllUsers
produces:
- application/json
parameters:
- name: x-access-token
in: header
description: Authorization token
required: true
type: string
responses:
'200':
description: Successfully got all users data
/users/signup:
post:
tags:
Expand Down
12 changes: 11 additions & 1 deletion tests/helpers.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable require-jsdoc */
import readingTime from 'read-time';
import { db } from '../server';
import { createFakeUsers } from '../db/faker';


/**
Expand Down Expand Up @@ -32,7 +33,7 @@ export class Response {

export const createUser = async (user) => {
const {
firstName, lastName, username, email, password
firstName, lastName, username, email, password, image, role
} = user;

const newUser = await db.User.create({
Expand All @@ -41,6 +42,8 @@ export const createUser = async (user) => {
username,
email,
password,
role,
image
});

return newUser;
Expand All @@ -54,3 +57,10 @@ export const createArticle = async article => db.Article.create({
export const createRate = async rating => db.Ratings.create(rating);

export const createArticleVote = async vote => db.ArticleVote.create(vote);

export const createTestFakeUsers = () => {
const users = createFakeUsers();
users.forEach(async (user) => {
await createUser(user);
});
};
32 changes: 31 additions & 1 deletion tests/routes/users.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import chaiHttp from 'chai-http';
import sinon from 'sinon';
import { transporter } from '../../utils/mailer';
import { app, db } from '../../server';
import { createUser } from '../helpers';
import { createUser, createTestFakeUsers } from '../helpers';
import * as utils from '../../utils';

let mockUploadImage;
Expand All @@ -23,6 +23,7 @@ describe('USER AUTHENTICATION', () => {
username: 'kev',
password: '12345678',
email: 'frank@gmail.com',
role: 'admin'
};

user = await createUser(register);
Expand Down Expand Up @@ -373,4 +374,33 @@ describe('USER AUTHENTICATION', () => {
expect(res).to.have.status(200);
});
});

describe('Get all Users', () => {
before(async () => {
await createTestFakeUsers();
Copy link
Contributor

Choose a reason for hiding this comment

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

Good job on using faker to generate data in your database to allow you test with. I think it would be good to clear the User table in your before block before running your test, since your test depends on the number of users it meets in the User table ---- line 391. This will avoid errors incase the User table had values before your test

Copy link
Contributor Author

Choose a reason for hiding this comment

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

There is no need for that because the user whose token is been used to access the endpoint is created at the top level before hook declared first within the test file. Token can't be gotten from the fake users created.

});
it('should get all first 20 users', async () => {
const { token } = user.response();
const res = await chai
.request(app)
.get('/api/v1/users')
.set('x-access-token', token);
expect(res.status).to.equal(200);
expect(res.body).to.be.an('object');
expect(res.body.users).to.be.an('array');
expect(res.body.users).to.have.length(20);
});

it('should get all second 10 users', async () => {
const { token } = user.response();
const res = await chai
.request(app)
.get('/api/v1/users?limit=10&offset=1')
.set('x-access-token', token);
expect(res.status).to.equal(200);
expect(res.body).to.be.an('object');
expect(res.body.users).to.be.an('array');
expect(res.body.users).to.have.length(10);
});
});
});