Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

inject middleware instead of using router #75

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ jobs:

e2e_memory:
runs-on: ubuntu-latest
needs: [linters]

steps:
- uses: actions/checkout@v2
Expand Down Expand Up @@ -81,7 +80,6 @@ jobs:

e2e_redis:
runs-on: ubuntu-latest
needs: [linters]

services:
redis:
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
"dev:memory": "yarn workspace @strapi-plugin-rest-cache/playground-memory develop",
"dev:redis": "yarn workspace @strapi-plugin-rest-cache/playground-redis develop",
"dev:couchbase": "yarn workspace @strapi-plugin-rest-cache/playground-couchbase develop",
"console:memory": "yarn workspace @strapi-plugin-rest-cache/playground-memory strapi console",
"console:redis": "yarn workspace @strapi-plugin-rest-cache/playground-redis strapi console",
"console:couchbase": "yarn workspace @strapi-plugin-rest-cache/playground-couchbase strapi console",
"profile:memory": "cd ./playgrounds/memory && 0x -o -D .profile -P 'autocannon --warmup [ -c 1 -d 3 ] -c 100 -p 10 -d 120 http://localhost:1337/api/homepage?populate=*' start-profiler.js",
"profile:redis": "cd ./playgrounds/redis && 0x -o -D .profile -P 'autocannon --warmup [ -c 1 -d 3 ] -c 100 -p 10 -d 120 http://localhost:1337/api/homepage?populate=*' start-profiler.js",
"profile:couchbase": "cd ./playgrounds/couchbase && 0x -o -D .profile -P 'autocannon --warmup [ -c 1 -d 3 ] -c 100 -p 10 -d 120 http://localhost:1337/api/homepage?populate=*' start-profiler.js",
Expand Down Expand Up @@ -71,4 +74,4 @@
"prettier --write"
]
}
}
}
85 changes: 2 additions & 83 deletions packages/strapi-plugin-rest-cache/server/bootstrap.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,13 @@
'use strict';

/**
* @typedef {import('@strapi/strapi').Strapi} Strapi
*/
const chalk = require('chalk');
const debug = require('debug');

const { CacheProvider } = require('./types');
const { resolveUserStrategy } = require('./utils/config/resolveUserStrategy');
const { createRouter } = require('./utils/middlewares/createRouter');

const permissionsActions = require('./permissions-actions');

const createProvider = async (providerConfig, { strapi }) => {
const providerName = providerConfig.name.toLowerCase();
let provider;

let modulePath;
try {
modulePath = require.resolve(`strapi-provider-rest-cache-${providerName}`);
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
modulePath = providerName;
} else {
throw error;
}
}

try {
// eslint-disable-next-line
provider = require(modulePath);
} catch (err) {
throw new Error(
`Could not load REST Cache provider "${providerName}". You may need to install a provider plugin "yarn add strapi-provider-rest-cache-${providerName}".`
);
}

const providerInstance = await provider.init(providerConfig.options, {
strapi,
});

if (!(providerInstance instanceof CacheProvider)) {
throw new Error(
`Could not load REST Cache provider "${providerName}". The package "strapi-provider-rest-cache-${providerName}" does not export a CacheProvider instance.`
);
}

return Object.freeze(providerInstance);
};

/**
* @param {{ strapi: Strapi }} strapi
*/
async function bootstrap({ strapi }) {
// resolve user configuration, check for missing or invalid options
const pluginOption = strapi.config.get('plugin.rest-cache');
const cacheStore = strapi.plugin('rest-cache').service('cacheStore');

if (pluginOption.strategy.debug === true) {
debug.enable('strapi:strapi-plugin-rest-cache');
}

const strategy = resolveUserStrategy(strapi, pluginOption.strategy);
strapi.config.set('plugin.rest-cache', {
...pluginOption,
strategy,
});

debug('strapi:strapi-plugin-rest-cache')('[STRATEGY]: %O', strategy);

const cacheStore = strapi.plugin('rest-cache').service('cacheStore');
// watch for changes in any roles -> clear all cache
// need to be done before lifecycles are registered
if (strapi.plugin('users-permissions')) {
Expand All @@ -79,32 +18,12 @@ async function bootstrap({ strapi }) {
},
});
}

// register cache provider
const provider = await createProvider(pluginOption.provider, { strapi });
strapi.plugin('rest-cache').service('cacheStore').init(provider);

// boostrap plugin permissions
await strapi.admin.services.permission.actionProvider.registerMany(
permissionsActions.actions
);

// boostrap cache middlewares
const router = createRouter(strapi, strategy);
strapi.server.router.use(router.routes());

strapi.log.info(
`Using REST Cache plugin with provider "${chalk.cyan(
pluginOption.provider.name
)}"`
);

if (strategy.resetOnStartup) {
strapi.log.warn('Reset cache on startup is enabled');
await strapi.plugin('rest-cache').service('cacheStore').reset();
}
}

module.exports = {
bootstrap,
bootstrap,
};
5 changes: 2 additions & 3 deletions packages/strapi-plugin-rest-cache/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ const { config } = require('./config');
const { controllers } = require('./controllers');
const { middlewares } = require('./middlewares');
const { routes } = require('./routes');
const { register } = require('./register')

module.exports = {
bootstrap,
destroy() {},
register,
config,
controllers,
routes,
services,
contentTypes: {},
policies: {},
middlewares,
};
91 changes: 91 additions & 0 deletions packages/strapi-plugin-rest-cache/server/register.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
'use strict';

/**
* @typedef {import('@strapi/strapi').Strapi} Strapi
*/
const chalk = require('chalk');
const debug = require('debug');

const { CacheProvider } = require('./types');
const { resolveUserStrategy } = require('./utils/config/resolveUserStrategy');
const { injectMiddlewares } = require('./utils/middlewares/injectMiddlewares');

const createProvider = async (providerConfig, { strapi }) => {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be moved back to bootstrap currently it will try to run this before the provider exists:

image

We can still register the middlewares but we can't create the provider until we get to the bootstrap.

const providerName = providerConfig.name.toLowerCase();
let provider;

let modulePath;
try {
modulePath = require.resolve(`strapi-provider-rest-cache-${providerName}`);
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
modulePath = providerName;
} else {
throw error;
}
}

try {
// eslint-disable-next-line
provider = require(modulePath);
} catch (err) {
throw new Error(
`Could not load REST Cache provider "${providerName}". You may need to install a provider plugin "yarn add strapi-provider-rest-cache-${providerName}".`
);
}

const providerInstance = await provider.init(providerConfig.options, {
strapi,
});

if (!(providerInstance instanceof CacheProvider)) {
throw new Error(
`Could not load REST Cache provider "${providerName}". The package "strapi-provider-rest-cache-${providerName}" does not export a CacheProvider instance.`
);
}

return Object.freeze(providerInstance);
};

/**
* @param {{ strapi: Strapi }} strapi
*/
async function register({ strapi }) {
// resolve user configuration, check for missing or invalid options
const pluginOption = strapi.config.get('plugin.rest-cache');
const cacheStore = strapi.plugin('rest-cache').service('cacheStore');

if (pluginOption.strategy.debug === true) {
debug.enable('strapi:strapi-plugin-rest-cache');
}

const strategy = resolveUserStrategy(strapi, pluginOption.strategy);
strapi.config.set('plugin.rest-cache', {
...pluginOption,
strategy,
});

debug('strapi:strapi-plugin-rest-cache')('[STRATEGY]: %O', strategy);

// register cache provider
const provider = await createProvider(pluginOption.provider, { strapi });
cacheStore.init(provider);

// boostrap cache middlewares
injectMiddlewares(strapi, strategy);

strapi.log.info(
`Using REST Cache plugin with provider "${chalk.cyan(
pluginOption.provider.name
)}"`
);

if (strategy.resetOnStartup) {
strapi.log.warn('Reset cache on startup is enabled');
await cacheStore.reset();
}
}

module.exports = {
register,
};
Loading
Loading