Skip to content

Commit fafd680

Browse files
author
hirsch88
committed
Fix wallaby and add some more tests
1 parent dae4290 commit fafd680

18 files changed

+419
-75
lines changed

.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ APP_NAME=express-typescript-boilerplate
55
APP_ENV=local
66
APP_HOST=http://localhost
77
APP_PORT=3000
8+
APP_URL_PREFIX=/api
89

910
#
1011
# LOGGING

src/api/controllers/UserController.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ import { my } from 'my-express';
44
import { Log } from '../../core/log';
55
import { UserService } from '../services/UsersService';
66
import { Types } from '../../constants/Types';
7-
import { authenticate } from '../middlewares/authenticate';
8-
import { populateUser } from '../middlewares/populateUser';
7+
import { authenticate, populateUser } from '../middlewares';
98

109
const log = new Log('api:ctrl.UserController');
1110

src/api/middlewares/authenticate.ts

Lines changed: 33 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import * as request from 'request';
1+
import { RequestAPI, RequiredUriUrl, Options, Request, RequestResponse } from 'request';
22
import { my } from 'my-express';
33
import { Log } from '../../core/log';
44

5-
const log = new Log('api:middleware.authenticate');
5+
// const log = new Log('api:middleware.authenticate');
66

77
/**
88
* authenticate middleware
@@ -13,38 +13,39 @@ const log = new Log('api:middleware.authenticate');
1313
* @param res
1414
* @param next
1515
*/
16-
export const authenticate = (req: my.Request, res: my.Response, next: my.NextFunction) => {
17-
const token = getToken(req);
16+
export const authenticate = (request: RequestAPI<Request, Options, RequiredUriUrl>, log: Log) =>
17+
(req: my.Request, res: my.Response, next: my.NextFunction) => {
18+
const token = getToken(req);
1819

19-
if (token === null) {
20-
log.warn('No token given');
21-
return res.failed(403, 'You are not allowed to request this resource!');
22-
}
23-
log.debug('Token is provided');
24-
25-
// Request user info at auth0 with the provided token
26-
request.post({
27-
url: `${process.env.AUTH0_HOST}/tokeninfo`,
28-
form: {
29-
id_token: token
20+
if (token === null) {
21+
log.warn('No token given');
22+
return res.failed(403, 'You are not allowed to request this resource!');
3023
}
31-
}, (error: any, response: request.RequestResponse, body: any) => {
32-
33-
// Verify if the requests was successful and append user
34-
// information to our extended express request object
35-
if (!error && response.statusCode === 200) {
36-
req.tokeninfo = JSON.parse(body);
37-
log.info(`Retrieved user ${req.tokeninfo.email}`);
38-
return next();
39-
}
40-
41-
// Catch auth0 exception and return it as it is
42-
log.warn(`Could not retrieve the user, because of`, body);
43-
res.failed(response.statusCode || 401, body);
44-
45-
});
46-
47-
};
24+
log.debug('Token is provided');
25+
26+
// Request user info at auth0 with the provided token
27+
request.post({
28+
url: `${process.env.AUTH0_HOST}/tokeninfo`,
29+
form: {
30+
id_token: token
31+
}
32+
}, (error: any, response: RequestResponse, body: any) => {
33+
34+
// Verify if the requests was successful and append user
35+
// information to our extended express request object
36+
if (!error && response.statusCode === 200) {
37+
req.tokeninfo = JSON.parse(body);
38+
log.info(`Retrieved user ${req.tokeninfo.email}`);
39+
return next();
40+
}
41+
42+
// Catch auth0 exception and return it as it is
43+
log.warn(`Could not retrieve the user, because of`, body);
44+
res.failed(response.statusCode || 401, body);
45+
46+
});
47+
48+
};
4849

4950
/**
5051
* Returns the access token of the given request header

src/api/middlewares/index.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import * as request from 'request';
2+
import container from '../../container';
3+
import { Log } from '../../core/log';
4+
import { Types } from '../../constants/Types';
5+
import { UserService } from '../services/UsersService';
6+
7+
import { authenticate as Authenticate } from './authenticate';
8+
import { populateUser as PopulateUser } from './populateUser';
9+
10+
11+
/**
12+
* Middlewares
13+
* ------------------------------------
14+
* We build them up here so we can easily use them in the controllers and
15+
* also be able to test the middlewares without any big effort.
16+
*/
17+
export const authenticate = Authenticate(request, new Log('api:middleware.authenticate'));
18+
export const populateUser = PopulateUser(() => container.get<UserService>(Types.UserService), new Log('api:middleware.populateUser'));
19+
Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import * as request from 'request';
2+
import { Container } from 'inversify';
23
import { my } from 'my-express';
34
import { Log } from '../../core/log';
45
import { UserService } from '../services/UsersService';
5-
import { Types } from '../../constants/Types';
6-
import container from '../../container';
76

8-
const log = new Log('api:middleware.populateUser');
7+
// const log = new Log('api:middleware.populateUser');
98

109
/**
1110
* populateUser middleware
@@ -17,21 +16,22 @@ const log = new Log('api:middleware.populateUser');
1716
* @param res
1817
* @param next
1918
*/
20-
export const populateUser = (req: my.Request, res: my.Response, next: my.NextFunction) => {
19+
export const populateUser = (lazyUserService: () => UserService, log: Log) =>
20+
(req: my.Request, res: my.Response, next: my.NextFunction) => {
2121

22-
if (!req.tokeninfo || !req.tokeninfo.user_id) {
23-
return res.failed(400, 'Missing token information!');
24-
}
22+
if (!req.tokeninfo || !req.tokeninfo.user_id) {
23+
return res.failed(400, 'Missing token information!');
24+
}
2525

26-
const userService = container.get<UserService>(Types.UserService);
27-
userService.findByUserId(req.tokeninfo.user_id)
28-
.then((user) => {
29-
req.user = user.toJSON();
30-
log.debug(`populated user with the id=${req.user.id} to the request object`);
31-
next();
32-
})
33-
.catch((error) => {
34-
log.warn(`could not populate user to the request object`);
35-
next(error);
36-
});
37-
};
26+
const userService = lazyUserService();
27+
userService.findByUserId(req.tokeninfo.user_id)
28+
.then((user) => {
29+
req.user = user.toJSON();
30+
log.debug(`populated user with the id=${req.user.id} to the request object`);
31+
next();
32+
})
33+
.catch((error) => {
34+
log.warn(`could not populate user to the request object`);
35+
next(error);
36+
});
37+
};

src/api/services/UsersService.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ const log = new Log('api:services:UserService');
1818
* database actions. Furthermore you should throw events here if
1919
* necessary.
2020
*
21-
* @export
21+
* @export0'
2222
* @class UserService
2323
*/
2424
@injectable()

src/core/Bootstrap.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export class Bootstrap {
4848
* @memberof Bootstrap
4949
*/
5050
static build(app: express.Application, container: Container): express.Application {
51-
let server = new InversifyExpressServer(container, undefined, { rootPath: '/api' }, app);
51+
let server = new InversifyExpressServer(container, undefined, { rootPath: Environment.get<string>('APP_URL_PREFIX') }, app);
5252
log.debug('ioc is bonded');
5353
server.setConfig((a) => a.use(extendExpressResponse));
5454
server.setErrorConfig((a) => a.use(exceptionHandler));

src/core/api/Exception.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ export class Exception extends Error {
2020
super(args[0]);
2121
this.code = code;
2222
this.name = this.constructor.name;
23-
this.message = args[0];
24-
this.body = args[1];
23+
this.message = args[0] || 'Unknown error' ;
24+
this.body = args[1] || null;
2525
this[isException] = true;
2626
Error.captureStackTrace(this);
2727
}

src/core/api/extendExpressResponse.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,17 @@ export const extendExpressResponse = (req: my.Request, res: my.Response, next: e
1414
* This is used for successful responses and a json body
1515
*/
1616
res.ok = <T>(data: T, options: my.ResponseOptions = {}) => {
17-
return res.status(200).json(bodySuccessful(data, options));
17+
res.status(200);
18+
return res.json(bodySuccessful(data, options));
1819
};
1920

2021
/**
2122
* 201 - Created
2223
* This is used for created resources
2324
*/
2425
res.created = <T>(data: T, options: my.ResponseOptions = {}) => {
25-
return res.status(201).json(bodySuccessful(data, options));
26+
res.status(201);
27+
return res.json(bodySuccessful(data, options));
2628
};
2729

2830
/**
@@ -46,15 +48,17 @@ export const extendExpressResponse = (req: my.Request, res: my.Response, next: e
4648
* This is the response after a resource has been removed
4749
*/
4850
res.destroyed = (options: my.ResponseOptions = {}) => {
49-
return res.status(204).json(bodySuccessful(null));
51+
res.status(204);
52+
return res.json(bodySuccessful(null));
5053
};
5154

5255
/**
5356
* 400-500 - Failed
5457
* This is used when a request has failed
5558
*/
5659
res.failed = (status: number, message: string, error?: any) => {
57-
return res.status(status).json(bodyFailed(message, error));
60+
res.status(status);
61+
return res.json(bodyFailed(message, error));
5862
};
5963

6064
next();

src/core/log/Log.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ export class Log {
6464
this.scope = (scope) ? scope : Log.DEFAULT_SCOPE;
6565
}
6666

67+
public getAdapter(): ILogAdapter {
68+
return this.adapter;
69+
}
70+
6771
public debug(message: string, ...args: any[]): void {
6872
this.log('debug', message, args);
6973
}

0 commit comments

Comments
 (0)