🛠️ createdBy と updatedBy などの作成者フィールドをポピュレートする
作成者フィールド createdBy と updatedBy は、既定では REST API のレスポンスから除かれています。コンテンツタイプで populateCreatorFields を有効にすると、REST API でこの 2 つを返せます。
Note
populateCreatorFields は GraphQL API では使えません。
ポピュレートされるのは次のフィールドのみです: id、firstname、lastname、username、preferedLanguage、createdAt、updatedAt。
createdBy と updatedBy を API レスポンスに含める手順:
- コンテンツタイプの
schema.jsonを開く。 optionsに"populateCreatorFields": trueを追加する。
"options": {
"draftAndPublish": true,
"populateCreatorFields": true
},
schema.jsonを保存する。- generate CLI を使うか、
./src/api/[content-type-name]/middlewares/[your-middleware-name].jsに手でファイルを作り、ルート用ミドルウェアを追加する。 - 次のコードを追加する(必要に応じて書き換えてください)。
./src/api/test/middlewares/defaultTestPopulate.js
"use strict";
module.exports = (config, { strapi }) => {
return async (ctx, next) => {
if (!ctx.query.populate) {
ctx.query.populate = ["createdBy", "updatedBy"];
}
await next();
};
};
- 既定のルートファクトリを変更し、このミドルウェアをポピュレートを適用したいルートだけで有効にする(コンテンツタイプ名・ミドルウェア名は自分のものに置き換える)。
./src/api/test/routes/test.js
"use strict";
const { createCoreRouter } = require("@strapi/strapi").factories;
module.exports = createCoreRouter("api::test.test", {
config: {
find: {
middlewares: ["api::test.default-test-populate"],
},
findOne: {
middlewares: ["api::test.default-test-populate"],
},
},
});
populate を付けない REST API リクエストでも、既定で createdBy と updatedBy が含まれるようになります。