get users

This commit is contained in:
2018-06-01 13:40:12 +03:00
parent 9c7907f1e8
commit 21477e3ef1
3 changed files with 31 additions and 1 deletions

View File

@@ -32,6 +32,13 @@ UserSchema.methods.generateJwt = function () {
return jwt.sign({ id: this._id, username: this.username }, secret, { expiresIn: '6m' });
};
UserSchema.methods.toJson = function () {
return {
id: this._id,
username: this.username,
};
};
UserSchema.methods.toAuthJson = function () {
return {
id: this._id,

View File

@@ -11,6 +11,16 @@ const auth = require('./auth');
const { NotFoundError } = require('../errors');
router.get(
'/user',
auth.required,
asyncHelper(async (req, res) => {
const { id } = req.user;
const user = await User.findById(id).exec();
res.json({ success: true, data: user.toJson() });
}),
);
router.post(
'/',
asyncHelper(async (req, res) => {

View File

@@ -14,6 +14,7 @@ const { seed, clean } = require('./utils');
const { secret } = require('../../config');
let token;
let user;
let mongoServer;
beforeAll(async () => {
@@ -23,7 +24,7 @@ beforeAll(async () => {
});
beforeEach(async () => {
({ token } = await seed());
({ token, user } = await seed());
});
afterEach(async () => {
@@ -37,6 +38,18 @@ afterAll(async () => {
});
describe('test users', () => {
test('should get user', async () => {
const response = await request(server)
.get('/users/user')
.set('Authorization', `Bearer ${token}`)
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
.expect(200)
.expect('Content-Type', 'application/json; charset=utf-8');
expect(response.body.success).toBeTruthy();
expect(response.body.data.id).toBe(user._id.toString());
expect(response.body.data.username).toBe(user.username);
});
test('should create user', async () => {
const response = await request(server)
.post('/users')