Last active
January 1, 2021 17:58
-
-
Save midnightcodr/4f66eb65906a59a60f321b2522e0c57a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Hapi = require('@hapi/hapi') | |
;(async () => { | |
const server = Hapi.server({ | |
port: 3000 | |
}) | |
server.events.on('log', logObject => { | |
console.log(JSON.stringify(logObject)) | |
}) | |
server.route({ | |
path: '/ip', | |
method: 'GET', | |
handler (request) { | |
// this works as expected | |
request.server.log('debug', 'got request') | |
/* | |
but the following codes won't work, got error below instead | |
Debug: internal, implementation, error | |
TypeError: Cannot read property '_core' of undefined | |
why? | |
*/ | |
// const { | |
// server: { log } | |
// } = request | |
// log('debug', 'got request') | |
return { | |
ip: request.info.remoteAddress | |
} | |
} | |
}) | |
await server.start() | |
console.log('start started at %s', server.info.uri) | |
})() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Logger.js | |
const levelMap = { | |
info: 1, | |
warning: 2, | |
error: 3 | |
} | |
class Logger { | |
constructor (options) { | |
// from low to high: info, warning, error | |
this.logLevel = (options && options.logLevel) || 'warning' | |
} | |
_logger (data) { | |
console.log( | |
'[%s] %s', | |
new Date().toLocaleString(), | |
typeof data === 'object' ? JSON.stringify(data) : data | |
) | |
} | |
log (info, level) { | |
if (levelMap[level] < levelMap[this.logLevel]) { | |
return | |
} | |
this._logger(info) | |
} | |
} | |
module.exports = Logger | |
// app.js | |
const Logger = require('./logger') | |
const logger = new Logger() | |
// this works | |
logger.log({hello: 'world'}, 'warning') | |
// this doesn't | |
const {log} = logger | |
log({hello: 'world'}, 'warning') | |
// reason being, Logger->log accesses member only attribute (this.logLevel) and method (this._logger) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment