Skip to content

Commit

Permalink
feat: breaking rewrite to support better structure
Browse files Browse the repository at this point in the history
  • Loading branch information
titanism committed Jun 2, 2022
1 parent 511bb09 commit 44948d1
Show file tree
Hide file tree
Showing 4 changed files with 601 additions and 159 deletions.
77 changes: 45 additions & 32 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const CacheResponses = require('@ladjs/koa-cache-responses');
const I18N = require('@ladjs/i18n');
const Koa = require('koa');
const Meta = require('koa-meta');
const Passport = require('@ladjs/passport');
const RedirectLoop = require('koa-redirect-loop');
const Redis = require('@ladjs/redis');
const StateHelper = require('@ladjs/state-helper');
Expand Down Expand Up @@ -70,7 +71,7 @@ const RATE_LIMIT_EXCEEDED = `Rate limit exceeded, retry in %s.`;

class Web {
// eslint-disable-next-line complexity
constructor(config, client) {
constructor(config, Users) {
this.config = {
...sharedConfig('WEB'),
meta: {},
Expand Down Expand Up @@ -169,38 +170,50 @@ class Web {
...config
};

const cabin = new Cabin({
logger: this.config.logger,
...this.config.cabin
});

// initialize redis
this.client = client
? client
: new Redis(this.config.redis, cabin, this.config.redisMonitor);

// initialize the app
const app = new Koa();

// allow middleware to access redis client
// only trust proxy if enabled
app.proxy = boolean(process.env.TRUST_PROXY);

// inherit cache variable for cache-pug-templates
app.cache = boolean(this.config.views.locals.cache);

// initialize cabin
this.logger = _.isPlainObject(this.config.logger)
? new Cabin(this.config.logger)
: this.config.logger instanceof Cabin
? this.config.logger
: new Cabin({
logger: this.config.logger ? this.config.logger : console
});
app.context.logger = this.logger;

// initialize redis
this.client =
this.config.redis === false
? false
: _.isPlainObject(this.config.redis)
? new Redis(this.config.redis, this.logger, this.config.redisMonitor)
: this.config.redis;
app.context.client = this.client;

// listen for error and log events emitted by app
// expose passport
this.passport =
this.config.passport === false
? false
: _.isPlainObject(this.config.passport)
? new Passport(this.config.passport, Users)
: this.config.passport;
app.context.passport = this.passport;

// listen for errors emitted by app
app.on('error', (err, ctx) => {
const level = err.status && err.status < 500 ? 'warn' : 'error';
if (ctx.logger) ctx.logger[level](err);
else cabin[level](err);
ctx.logger[err.status && err.status < 500 ? 'warn' : 'error'](err);
});
app.on('log', cabin.log);

// override koa's undocumented error handler
app.context.onerror = errorHandler(this.config.cookiesKey, cabin);

// only trust proxy if enabled
app.proxy = boolean(process.env.TRUST_PROXY);

// inherit cache variable for cache-pug-templates
app.cache = boolean(this.config.views.locals.cache);
app.context.onerror = errorHandler(this.config.cookiesKey);

// adds request received hrtime and date symbols to request object
// (which is used by Cabin internally to add `request.timestamp` to logs
Expand All @@ -219,7 +232,7 @@ class Web {
app.use(koaConnect(requestId()));

// add cabin middleware
app.use(cabin.middleware);
app.use(this.logger.middleware);

// allow before hooks to get setup
if (_.isFunction(this.config.hookBeforeSetup))
Expand All @@ -243,7 +256,7 @@ class Web {
return ratelimit({
...this.config.rateLimit,
db: this.client,
logger: cabin,
logger: this.logger,
errorMessage(exp) {
const fn =
typeof ctx.request.t === 'function' ? ctx.request.t : util.format;
Expand All @@ -266,7 +279,7 @@ class Web {
// create new @ladjs/i18n instance
const i18n = this.config.i18n.config
? this.config.i18n
: new I18N({ ...this.config.i18n, logger: cabin });
: new I18N({ ...this.config.i18n, logger: this.logger });

// setup localization (must come before `i18n.redirect`)
app.use(i18n.middleware);
Expand Down Expand Up @@ -321,7 +334,7 @@ class Web {
// NOTE: this must come after ctx.render is added (via koa-views)
//
if (this.config.meta) {
const meta = new Meta(this.config.meta, cabin);
const meta = new Meta(this.config.meta, this.logger);
app.use(meta.middleware);
}

Expand Down Expand Up @@ -396,15 +409,15 @@ class Web {
}

// passport
if (this.config.passport) {
app.use(this.config.passport.initialize());
app.use(this.config.passport.session());
if (this.passport) {
app.use(this.passport.initialize());
app.use(this.passport.session());
}

// store the user's last ip address in the background
if (this.config.storeIPAddress) {
const storeIPAddress = new StoreIPAddress({
logger: cabin,
logger: this.logger,
...this.config.storeIPAddress
});
app.use(storeIPAddress.middleware);
Expand Down
13 changes: 7 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"@ladjs/koa-isajax": "^2.0.0",
"@ladjs/koa-simple-ratelimit": "^3.0.0",
"@ladjs/redis": "^1.0.7",
"@ladjs/shared-config": "^7.0.0",
"@ladjs/shared-config": "^7.0.3",
"@ladjs/state-helper": "^1.0.0",
"@ladjs/store-ip-address": "^0.0.7",
"boolean": "^3.2.0",
Expand Down Expand Up @@ -67,20 +67,21 @@
"response-time": "^2.3.2"
},
"devDependencies": {
"@commitlint/cli": "^17.0.1",
"@commitlint/config-conventional": "^17.0.0",
"ava": "^4.2.0",
"@commitlint/cli": "^17.0.2",
"@commitlint/config-conventional": "^17.0.2",
"@ladjs/passport": "^5.0.0",
"ava": "^4.3.0",
"codecov": "^3.8.3",
"cross-env": "^7.0.3",
"eslint": "^8.16.0",
"eslint-config-xo-lass": "^1.0.6",
"fixpack": "^4.0.0",
"husky": "^8.0.1",
"lint-staged": "^12.4.3",
"lint-staged": "^13.0.0",
"nyc": "^15.1.0",
"pug": "^3.0.2",
"remark-cli": "^10.0.1",
"remark-preset-github": "^4.0.1",
"remark-preset-github": "^4.0.2",
"supertest": "^6.2.3",
"xo": "^0.49.0"
},
Expand Down
31 changes: 29 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const test = require('ava');
const request = require('supertest');
const Passport = require('@ladjs/passport');
const Router = require('@koa/router');
const request = require('supertest');
const test = require('ava');

const Web = require('..');

test('allows custom routes', async (t) => {
Expand Down Expand Up @@ -42,3 +44,28 @@ test('default method override', async (t) => {
t.is(response.body.method, 'put');
t.is(response.request.method, 'POST');
});

test('with redis instance', (t) => {
const api = new Web();
t.is(typeof api.client, 'object');
t.is(typeof api.app.context.client, 'object');
});

test('without redis instance', (t) => {
const api = new Web({ redis: false });
t.is(api.client, false);
t.is(api.app.context.client, false);
});

test('with passport instance', (t) => {
const passport = new Passport({});
const api = new Web({ passport });
t.is(typeof api.passport, 'object');
t.is(typeof api.app.context.passport, 'object');
});

test('without passport instance', (t) => {
const api = new Web();
t.is(api.passport, false);
t.is(api.app.context.passport, false);
});
Loading

0 comments on commit 44948d1

Please sign in to comment.