Last active
May 16, 2021 23:21
-
-
Save thopedam/31e65be1f757c68fc3230b6de82b6b98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const { has, prop, pick, concat } = require("lodash/fp"); | |
const { | |
PUBLISHED_AT_ATTRIBUTE, | |
} = require("strapi-utils").contentTypes.constants; | |
const { getService } = require("strapi-plugin-content-manager/utils"); | |
module.exports = { | |
async find(ctx) { | |
const { model, targetField } = ctx.params; | |
const { _component, ...query } = ctx.request.query; | |
const { idsToOmit } = ctx.request.body; | |
const { user } = ctx.state; | |
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"); | |
} | |
if (idsToOmit && Array.isArray(idsToOmit)) { | |
query._where = query._where || {}; | |
query._where.id_nin = concat(query._where.id_nin || [], idsToOmit); | |
} | |
const entityManager = getService("entity-manager"); | |
let entities = []; | |
if (user.roles[0].code !== 'strapi-super-admin') { | |
query['created_by'] = `${user.id}`; | |
} | |
if (has("_q", ctx.request.query)) { | |
entities = await entityManager.search(query, target.uid); | |
} else { | |
entities = await entityManager.find(query, target.uid); | |
} | |
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)); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment