メインコンテンツまでスキップ

🛠️ createdByupdatedBy などの作成者フィールドをポピュレートする

作成者フィールド createdByupdatedBy は、既定では REST API のレスポンスから除かれています。コンテンツタイプで populateCreatorFields を有効にすると、REST API でこの 2 つを返せます。

Note

populateCreatorFields は GraphQL API では使えません。

ポピュレートされるのは次のフィールドのみです: idfirstnamelastnameusernamepreferedLanguagecreatedAtupdatedAt

createdByupdatedBy を API レスポンスに含める手順:

  1. コンテンツタイプの schema.json を開く。
  2. options"populateCreatorFields": true を追加する。
"options": {
"draftAndPublish": true,
"populateCreatorFields": true
},
  1. schema.json を保存する。
  2. generate CLI を使うか、./src/api/[content-type-name]/middlewares/[your-middleware-name].js に手でファイルを作り、ルート用ミドルウェアを追加する。
  3. 次のコードを追加する(必要に応じて書き換えてください)。
./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();
};
};
  1. 既定のルートファクトリを変更し、このミドルウェアをポピュレートを適用したいルートだけで有効にする(コンテンツタイプ名・ミドルウェア名は自分のものに置き換える)。
./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 リクエストでも、既定で createdByupdatedBy が含まれるようになります。