Ghost/ghost/limit-service/lib/limit-service.js
Hannah Wolfe 2163ec6057 Changed casing of limit names + fixed handling
refs: https://github.com/TryGhost/Team/issues/510

- Ghost config always uses camelcase. This was incorrectly implemented with snake case originally
- Swap to use camelCase by default, which is desirable, but support both
- It's really easy to support both in the loader and isLimited check, so we do this to stop ourselves tripping on this later
2021-03-04 20:39:09 +00:00

79 lines
2.0 KiB
JavaScript

const errors = require('@tryghost/errors');
const {MaxLimit, FlagLimit} = require('./limit');
const config = require('./config');
const _ = require('lodash');
class LimitService {
constructor() {
this.limits = {};
}
loadLimits({limits, helpLink, db}) {
Object.keys(limits).forEach((name) => {
name = _.camelCase(name);
if (config[name]) {
let limitConfig = _.merge({}, limits[name], config[name]);
if (_.has(limitConfig, 'max')) {
this.limits[name] = new MaxLimit({name: name, config: limitConfig, helpLink, db});
} else {
this.limits[name] = new FlagLimit({name: name, config: limitConfig, helpLink});
}
}
});
}
isLimited(limitName) {
return !!this.limits[_.camelCase(limitName)];
}
async checkIsOverLimit(limitName) {
if (!this.isLimited(limitName)) {
return;
}
try {
await this.limits[limitName].errorIfIsOverLimit();
return false;
} catch (error) {
if (error instanceof errors.HostLimitError) {
return true;
}
}
}
async checkWouldGoOverLimit(limitName) {
if (!this.isLimited(limitName)) {
return;
}
try {
await this.limits[limitName].errorIfWouldGoOverLimit();
return false;
} catch (error) {
if (error instanceof errors.HostLimitError) {
return true;
}
}
}
async errorIfIsOverLimit(limitName) {
if (!this.isLimited(limitName)) {
return;
}
await this.limits[limitName].errorIfIsOverLimit();
}
async errorIfWouldGoOverLimit(limitName) {
if (!this.isLimited(limitName)) {
return;
}
await this.limits[limitName].errorIfWouldGoOverLimit();
}
}
module.exports = LimitService;