Skip to content

Commit

Permalink
General adjustments
Browse files Browse the repository at this point in the history
- Updated versions of the dependencies used in the project;
- Updated some tests.
  • Loading branch information
douglasrafael committed Jan 29, 2020
1 parent d0807b9 commit 33cc3b5
Show file tree
Hide file tree
Showing 15 changed files with 1,086 additions and 674 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Application settings are defined by environment variables. To define the setting
| `RABBITMQ_CA_PATH` | RabbitMQ CA file location. Must always be provided when using `amqps` protocol. | `.certs/rabbitmqca.crt` |
| `FITBIT_CLIENT_ID` | Client Id for Fitbit Application resposible to manage user data. | `CIENT_ID_HERE` |
| `FITBIT_CLIENT_SECRET` | Client Secret for Fitbit Application resposible to manage user data. | `CIENT_SECRET_HERE` |
| `FITBIT_CLIENT_SUBSCRIBER` | Client Subscriber code for automatically get notification from new sync data. | `CLIENT_SUBSCRIBER_HERE` |
| `FITBIT_CLIENT_SUBSCRIBER` | Code used by Fitbit to verify the subscriber. | `CLIENT_SUBSCRIBER_HERE` |
| `FITBIT_SUBSCRIBER_ID` | Customer Subscriber ID, used to manage the subscriber who will receive notification of a user resource. | `FITBIT_SUBSCRIBER_ID` |
| `EXPRESSION_AUTO_SYNC` | Defines how often the application will automatically sync user data in the background according to the crontab expression. | `0 0 * * 0` |

Expand Down
1,301 changes: 761 additions & 540 deletions package-lock.json

Large diffs are not rendered by default.

28 changes: 14 additions & 14 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "data-sync-agent",
"version": "1.5.5",
"version": "1.5.6",
"description": "Service responsible for data synchronization of FitBit and CVE platform with OCARIoT platform.",
"main": "dist/server.js",
"scripts": {
Expand Down Expand Up @@ -53,8 +53,8 @@
"all": true
},
"dependencies": {
"@ocariot/rabbitmq-client-node": "^1.4.0",
"axios": "^0.19.0",
"@ocariot/rabbitmq-client-node": "1.4.0",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"bull": "^3.12.1",
"dotenv": "^8.2.0",
Expand All @@ -65,38 +65,38 @@
"inversify-express-utils": "^6.3.2",
"jsonwebtoken": "^8.5.1",
"moment": "^2.24.0",
"mongoose": "^5.7.13",
"mongoose": "5.8.2",
"morgan": "^1.9.1",
"node-cron": "^2.0.3",
"query-strings-parser": "^2.1.3",
"reflect-metadata": "^0.1.13",
"swagger-ui-express": "^4.1.2",
"swagger-ui-express": "^4.1.3",
"winston": "^3.2.1",
"winston-daily-rotate-file": "^4.3.0"
"winston-daily-rotate-file": "^4.4.2"
},
"devDependencies": {
"@types/body-parser": "^1.17.1",
"@types/bull": "^3.10.6",
"@types/chai": "^4.2.5",
"@types/chai": "^4.2.7",
"@types/express": "^4.17.2",
"@types/helmet": "^0.0.45",
"@types/mocha": "^5.2.7",
"@types/mongoose": "^5.5.32",
"@types/mongoose": "^5.5.43",
"@types/morgan": "^1.7.37",
"@types/swagger-ui-express": "^4.1.0",
"@types/swagger-ui-express": "^4.1.1",
"chai": "^4.2.0",
"gulp": "^4.0.2",
"gulp-nodemon": "^2.4.2",
"gulp-tslint": "^8.1.4",
"gulp-typescript": "^5.0.1",
"mocha": "^6.2.2",
"nyc": "^14.1.1",
"nyc": "^15.0.0",
"sinon": "^7.5.0",
"sinon-mongoose": "^2.3.0",
"supertest": "^4.0.2",
"ts-node": "^8.5.2",
"tslint": "^5.20.1",
"typedoc": "^0.15.3",
"typescript": "^3.7.2"
"ts-node": "^8.6.2",
"tslint": "^6.0.0",
"typedoc": "^0.16.9",
"typescript": "^3.7.5"
}
}
35 changes: 17 additions & 18 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ export class App {
* @private
* @return void
*/
private async initMiddleware(): Promise<void> {
private initMiddleware(): void {
try {
await this.setupInversifyExpress()
this.setupInversifyExpress()
this.setupSwaggerUI()
this.setupErrorsHandler()
} catch (err) {
Expand All @@ -75,7 +75,7 @@ export class App {
* @private
* @return Promise<void>
*/
private async setupInversifyExpress(): Promise<void> {
private setupInversifyExpress(): void {
const inversifyExpress: InversifyExpressServer = new InversifyExpressServer(
DIContainer, null, { rootPath: '/' })

Expand Down Expand Up @@ -117,15 +117,13 @@ export class App {
*/
private setupSwaggerUI(): void {
// Middleware swagger. It should not run in the test environment.
if ((process.env.NODE_ENV || Default.NODE_ENV) !== 'test') {
const options = {
swaggerUrl: Default.SWAGGER_URI,
customCss: '.swagger-ui .topbar { display: none }',
customfavIcon: Default.LOGO_URI,
customSiteTitle: `API Reference | ${Strings.APP.TITLE}`
}
this.express.use('/v1/reference', swaggerUi.serve, swaggerUi.setup({}, options))
const options = {
swaggerUrl: Default.SWAGGER_URI,
customCss: '.swagger-ui .topbar { display: none }',
customfavIcon: Default.LOGO_URI,
customSiteTitle: `API Reference | ${Strings.APP.TITLE}`
}
this.express.use('/v1/reference', swaggerUi.serve, swaggerUi.setup({}, options))
}

/**
Expand All @@ -137,9 +135,11 @@ export class App {
private setupErrorsHandler(): void {
// Handle 404
this.express.use((req, res) => {
const errorMessage: ApiException = new ApiException(404, `${req.url} not found.`,
`Specified resource: ${req.url} was not found or does not exist.`)
res.status(HttpStatus.NOT_FOUND).send(errorMessage.toJson())
const errorMessage: ApiException = new ApiException(
404,
Strings.ERROR_MESSAGE.ENDPOINT_NOT_FOUND.replace('{0}', req.url)
)
res.status(HttpStatus.NOT_FOUND).send(errorMessage.toJSON())
})

// Handle 400, 500
Expand All @@ -149,11 +149,10 @@ export class App {
if (err && err.statusCode === HttpStatus.BAD_REQUEST) {
statusCode = HttpStatus.BAD_REQUEST
errorMessage.code = statusCode
errorMessage.message = 'Unable to process request body.'
errorMessage.description = 'Please verify that the JSON provided in'
.concat(' the request body has a valid format and try again.')
errorMessage.message = Strings.ERROR_MESSAGE.REQUEST_BODY_INVALID
errorMessage.description = Strings.ERROR_MESSAGE.REQUEST_BODY_INVALID_DESC
}
res.status(statusCode).send(errorMessage.toJson())
res.status(statusCode).send(errorMessage.toJSON())
})
}
}
2 changes: 1 addition & 1 deletion src/ui/controllers/home.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ export class HomeController {
*/
@httpGet('/')
public getReference(@request() req: Request, @response() res: Response): void {
return res.redirect('/v1/reference')
return res.redirect(301, '/v1/reference')
}
}
8 changes: 4 additions & 4 deletions src/ui/controllers/user.fitbit.auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class UserFitbitAuthController {
return res.status(HttpStatus.NO_CONTENT).send()
} catch (err) {
const handlerError = ApiExceptionManager.build(err)
return res.status(handlerError.code).send(handlerError.toJson())
return res.status(handlerError.code).send(handlerError.toJSON())
}
}

Expand All @@ -63,13 +63,13 @@ export class UserFitbitAuthController {
HttpStatus.NOT_FOUND,
Strings.FITBIT.AUTH_NOT_FOUND,
Strings.FITBIT.AUTH_NOT_FOUND_DESCRIPTION
).toJson()
).toJSON()
)
}
return res.status(HttpStatus.OK).send(this.toJsonView(result))
} catch (err) {
const handlerError = ApiExceptionManager.build(err)
return res.status(handlerError.code).send(handlerError.toJson())
return res.status(handlerError.code).send(handlerError.toJSON())
}
}

Expand All @@ -85,7 +85,7 @@ export class UserFitbitAuthController {
return res.status(HttpStatus.NO_CONTENT).send()
} catch (err) {
const handlerError = ApiExceptionManager.build(err)
return res.status(handlerError.code).send(handlerError.toJson())
return res.status(handlerError.code).send(handlerError.toJSON())
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/ui/controllers/user.fitbit.sync.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class UserFitbitSyncController {
return res.status(HttpStatus.ACCEPTED).send(result.toJSON())
} catch (err) {
const handlerError = ApiExceptionManager.build(err)
return res.status(handlerError.code).send(handlerError.toJson())
return res.status(handlerError.code).send(handlerError.toJSON())
}
}
}
2 changes: 1 addition & 1 deletion src/ui/exception/api.exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class ApiException extends Exception {
*
* @return Object
*/
public toJson(): object {
public toJSON(): object {
return {
code: this.code,
message: this.message,
Expand Down
82 changes: 54 additions & 28 deletions src/utils/custom.logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,49 @@ import DailyRotateFile from 'winston-daily-rotate-file'

@injectable()
export class CustomLogger implements ILogger {
private readonly _logger: Logger
public readonly _logger: Logger
private readonly _logDir = process.env.LOG_DIR || Default.LOG_DIR
private readonly _moduleName: string
private _moduleName: string = Default.APP_ID
private _options: any = {}

constructor() {
if (!fs.existsSync(this._logDir)) fs.mkdirSync(this._logDir) // create directory if it does not exist
this.initOptions() // initialize options logger
this._logger = this.internalCreateLogger()
this._moduleName = 'ds.app'
}

set moduleName(value: string) {
this._moduleName = value
}

get moduleName(): string {
return this._moduleName
}

private internalCreateLogger(): Logger {
const errorFormat = format((info: any) => {
if (info instanceof Error) {
info = info as Error
return Object.assign({
message: info.message.concat(info.description ? ` | ${info.description}` : ''),
stack: info.stack
}, info)
}
return info
})

return createLogger({
level: 'silly', // Used by transports that do not have this configuration defined
silent: false,
format: format.combine(
errorFormat(),
format.timestamp(),
format.json()
),
transports: [new transports.Console(this._options), this.createTransportDailyRotateFile()],
exceptionHandlers: [
new transports.File({ filename: 'exceptions.log' })
],
exitOnError: false
})
}
Expand All @@ -38,7 +60,7 @@ export class CustomLogger implements ILogger {
format.colorize(),
format.splat(),
format.timestamp(),
format.printf(log => `${log.module} @ ${log.timestamp} ${log.level}: ${log.message}`)
format.printf(log => `${this._moduleName} @ ${log.timestamp} ${log.level}: ${log.message}`)
)
}

Expand All @@ -65,28 +87,36 @@ export class CustomLogger implements ILogger {
return this._logger.add(transport)
}

public error(message: string): void {
this._logger.error(message, { module: this._moduleName })
}

public warn(message: string): void {
this._logger.warn(message, { module: this._moduleName })
}

public info(message: string): void {
this._logger.info(message, { module: this._moduleName })
public error(message: string | object): void {
if (typeof message === 'string') {
this._logger.error(message)
return
}
this._logger.error(message)
}

public verbose(message: string): void {
this._logger.verbose(message, { module: this._moduleName })
public warn(message: string | object): void {
if (typeof message === 'string') {
this._logger.warn(message)
return
}
this._logger.warn(message)
}

public debug(message: string): void {
this._logger.debug(message, { module: this._moduleName })
public info(message: string | object): void {
if (typeof message === 'string') {
this._logger.info(message)
return
}
this._logger.info(message)
}

public silly(message: string): void {
this._logger.silly(message, { module: this._moduleName })
public debug(message: string | object): void {
if (typeof message === 'string') {
this._logger.debug(message)
return
}
this._logger.debug(message)
}
}

Expand All @@ -103,17 +133,13 @@ export class CustomLogger implements ILogger {
* @see {@link https://github.com/winstonjs/winston#using-logging-levels} for further information.
*/
export interface ILogger {
error(message: string): void

warn(message: string): void

info(message: string): void
error(message: string | object): void

verbose(message: string): void
warn(message: string | object): void

debug(message: string): void
info(message: string | object): void

silly(message: string): void
debug(message: string | object): void

addTransport(transport: any): Logger
}
1 change: 1 addition & 0 deletions src/utils/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* @abstract
*/
export abstract class Default {
public static readonly APP_ID: string = 'ds.app'
public static readonly APP_TITLE: string = 'OCARIoT Data Sync Agent Service'
public static readonly APP_DESCRIPTION: string = 'Microservice responsible for data synchronization of FitBit ' +
'and CVE platform with OCARIoT platform.'
Expand Down
3 changes: 3 additions & 0 deletions src/utils/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export abstract class Strings {
}

public static readonly ERROR_MESSAGE: any = {
ENDPOINT_NOT_FOUND: 'Endpoint {0} does not found!',
REQUEST_BODY_INVALID: 'Unable to process request body!',
REQUEST_BODY_INVALID_DESC: 'Please verify that the JSON provided in the request body has a valid format and try again.',
UNEXPECTED: 'An unexpected error has occurred. Please try again later...',
UUID_NOT_VALID_FORMAT: 'Some ID provided does not have a valid format!',
UUID_NOT_VALID_FORMAT_DESC: 'A 24-byte hex ID similar to this: 507f191e810c19729de860ea is expected.',
Expand Down
Loading

0 comments on commit 33cc3b5

Please sign in to comment.