Reset loaders on every request to avoid wrong results coming from cache

This commit is contained in:
Aurélien Georget 2019-01-05 18:14:00 +01:00
parent 53b195c917
commit 2df5ecae79
3 changed files with 25 additions and 5 deletions

View File

@ -12,8 +12,26 @@ const DataLoader = require('dataloader');
module.exports = {
loaders: {},
createLoader: function(model) {
this.loaders[model] = new DataLoader(keys => {
initializeLoader: function() {
// Create loaders for each relational field (exclude core models).
Object.keys(strapi.models)
.filter(model => model !== 'core_store')
.forEach(model => {
(strapi.models[model].associations || []).forEach(association => this.createLoader(association.collection || association.model, association.plugin));
});
// Reproduce the same pattern for each plugin.
Object.keys(strapi.plugins).forEach(plugin => {
Object.keys(strapi.plugins[plugin].models).forEach(model => {
(strapi.plugins[plugin].models[model].associations || []).forEach(association => this.createLoader(association.collection || association.model, association.plugin));
});
});
},
createLoader: function(model, plugin) {
const name = plugin ? `${plugin}__${model}`: model;
this.loaders[name] = new DataLoader(keys => {
return new Promise(async (resolve, reject) => {
try {
// Extract queries from keys and merge similar queries.

View File

@ -10,6 +10,8 @@ const _ = require('lodash');
const pluralize = require('pluralize');
const policyUtils = require('strapi-utils').policy;
const Loaders = require('./Loaders');
module.exports = {
/**
* Convert parameters to valid filters parameters.
@ -256,6 +258,9 @@ module.exports = {
return policy;
}
// Initiliase loaders for this request.
Loaders.initializeLoader();
// Resolver can be a function. Be also a native resolver or a controller's action.
if (_.isFunction(resolver)) {
context.query = this.convertToParams(options);

View File

@ -362,9 +362,6 @@ module.exports = {
default:
}
// Create dynamic dataloader for query batching and caching.
Loaders.createLoader(association.collection || association.model, association.plugin);
_.merge(acc.resolver[globalId], {
[association.alias]: async (obj, options) => {
// eslint-disable-line no-unused-vars