2020-10-27 16:01:46 +01:00
|
|
|
'use strict';
|
|
|
|
|
2021-01-25 17:58:18 +01:00
|
|
|
const { has, prop, pick, concat } = require('lodash/fp');
|
2020-10-27 16:01:46 +01:00
|
|
|
const { PUBLISHED_AT_ATTRIBUTE } = require('strapi-utils').contentTypes.constants;
|
|
|
|
|
|
|
|
const { getService } = require('../utils');
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
async find(ctx) {
|
|
|
|
const { model, targetField } = ctx.params;
|
|
|
|
const { _component, ...query } = ctx.request.query;
|
2021-01-25 17:58:18 +01:00
|
|
|
const { idsToOmit } = ctx.request.body;
|
2020-10-27 16:01:46 +01:00
|
|
|
|
|
|
|
if (!targetField) {
|
|
|
|
return ctx.badRequest();
|
|
|
|
}
|
|
|
|
|
|
|
|
const modelDef = _component ? strapi.db.getModel(_component) : strapi.db.getModel(model);
|
|
|
|
|
|
|
|
if (!modelDef) {
|
|
|
|
return ctx.notFound('model.notFound');
|
|
|
|
}
|
|
|
|
|
|
|
|
const attr = modelDef.attributes[targetField];
|
|
|
|
if (!attr) {
|
|
|
|
return ctx.badRequest('targetField.invalid');
|
|
|
|
}
|
|
|
|
|
|
|
|
const target = strapi.db.getModelByAssoc(attr);
|
|
|
|
|
|
|
|
if (!target) {
|
|
|
|
return ctx.notFound('target.notFound');
|
|
|
|
}
|
|
|
|
|
2021-01-25 17:58:18 +01:00
|
|
|
if (idsToOmit && Array.isArray(idsToOmit)) {
|
|
|
|
query._where = query._where || {};
|
|
|
|
query._where.id_nin = concat(query._where.id_nin || [], idsToOmit);
|
|
|
|
}
|
|
|
|
|
2020-11-02 21:13:50 +01:00
|
|
|
const entityManager = getService('entity-manager');
|
2020-10-27 16:01:46 +01:00
|
|
|
|
|
|
|
let entities = [];
|
|
|
|
|
|
|
|
if (has('_q', ctx.request.query)) {
|
2020-11-02 21:13:50 +01:00
|
|
|
entities = await entityManager.search(query, target.uid);
|
2020-10-27 16:01:46 +01:00
|
|
|
} else {
|
2020-11-02 21:13:50 +01:00
|
|
|
entities = await entityManager.find(query, target.uid);
|
2020-10-27 16:01:46 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!entities) {
|
|
|
|
return ctx.notFound();
|
|
|
|
}
|
|
|
|
|
|
|
|
const modelConfig = _component
|
|
|
|
? await getService('components').findConfiguration(modelDef)
|
|
|
|
: await getService('content-types').findConfiguration(modelDef);
|
|
|
|
|
|
|
|
const field = prop(`metadatas.${targetField}.edit.mainField`, modelConfig) || 'id';
|
|
|
|
const pickFields = [field, 'id', target.primaryKey, PUBLISHED_AT_ATTRIBUTE];
|
|
|
|
|
|
|
|
ctx.body = entities.map(pick(pickFields));
|
|
|
|
},
|
|
|
|
};
|