typescript - เป็นไปได้ไหมที่จะทำให้ lifecycle hooks ของ strapi v4 มีความปลอดภัยด้านประเภท?
ฉันกำลังพยายามเพิ่มชนิดให้กับ lifecycle ของ Strapi จนถึงตอนนี้ฉันยังไม่พบอะไรที่เป็นประโยชน์ในเอกสารหรือการค้นหาใน Google
// foo/lifecycle.js
export default {
afterCreate: (event: any) => {
// event.result to be typed
},
};
เป็นไปได้ไหมที่จะได้ประเภทของเหตุการณ์จากบางที่ที่ซ่อนอยู่ใน @strapi/strapi ? โดยบอกไว้เลยว่าฉันกำลังใช้เวอร์ชัน 4
คำตอบ #1
ฉันสามารถพิมพ์เหตุการณ์วงจรชีวิตได้ดังนี้:
import { Attribute } from '@strapy/types';
import { Event } from '@strapi/database/dist/lifecycles';
type LifecycleEvent<T> = Event & {
result?: T; // since result is only available in `afterXXX` events
}
type MyEvent = LifecycleEvent<Attribute.GetValues<'api::admin.admin'>>;
export default {
beforeCreate: async (event: MyEvent) => {
await validateData(event);
},
beforeUpdate: async (event: MyEvent) => {
event.state.updatedFields = await getUpdatedFields(event);
},
afterUpdate: async (event: MyEvent) => {
await syncData(event);
},
};
คำตอบ #2
ณ เวอร์ชัน 5 ของ Strapi โครงสร้างการตอบกลับได้มีการเปลี่ยนแปลงเล็กน้อย รูปแบบการตอบกลับถูกทำให้แบนราบ ซึ่งหมายความว่าคุณสมบัติไม่อยู่ในวัตถุ data.attributes ซ้อนกันอีกต่อไป คุณสามารถดูข้อมูลนี้และข้อมูลอื่น ๆ ได้ที่นี่: https://docs.strapi.io/dev-docs/api/rest#requests
import * as AttributeUtils from "@strapi/types/dist/modules/documents/params/attributes";
import * as UID from "@strapi/types/dist/uid";
import { Event, Params } from "@strapi/database/dist/lifecycles";
type LifecycleEvent<T extends UID.Schema> = Omit<Event, "result" | "params"> & {
result?: AttributeUtils.GetValues<T>;
params: Omit<Params, "data"> & {
data: Omit<
AttributeUtils.GetValues<T>,
"id" | "documentId" | "localizations" | "locale"
>;
};
};
type TypedEvent = LifecycleEvent<"admin::user">; //change this
export default {
async beforeCreate(event: TypedEvent) {
// event.params is typed here
},
async afterCreate(event: TypedEvent) {
// event.result is typed here
},
};
