diff --git a/src/api/commentaire/content-types/commentaire/__tests__/lifecycles.test.js b/src/api/commentaire/content-types/commentaire/__tests__/lifecycles.test.js index 790abb3..5c6d0c2 100644 --- a/src/api/commentaire/content-types/commentaire/__tests__/lifecycles.test.js +++ b/src/api/commentaire/content-types/commentaire/__tests__/lifecycles.test.js @@ -27,11 +27,33 @@ describe('commentaire afterCreate — notification email', () => { const {afterCreate} = await loadLifecycles(strapiMock); - await afterCreate({params: {data: {user: 1, parole: 7, contenu: ''}}}); + await afterCreate({params: {data: {user: {connect: [{id: 1}]}, parole: {connect: [{id: 7}]}, contenu: ''}}}); expect(emailSend).toHaveBeenCalledTimes(1); const [payload] = emailSend.mock.calls[0]; expect(payload.text).toBe(''); expect(payload.html).toBeUndefined(); }); + + it('extrait l\'id de la relation quelle que soit sa forme (connect, set, id brut)', async () => { + const paroleFindOne = vi.fn(async ({where}) => ({id: where.id, titre: 'Mon titre'})); + const strapiMock = { + db: { + query: vi.fn(uid => { + if (uid === 'plugin::users-permissions.user') return {findOne: vi.fn(async () => null)}; + if (uid === 'api::parole.parole') return {findOne: paroleFindOne}; + throw new Error(`unexpected uid: ${uid}`); + }) + }, + plugins: {email: {services: {email: {send: vi.fn()}}}} + }; + + const {afterCreate} = await loadLifecycles(strapiMock); + + await afterCreate({params: {data: {parole: {set: [{id: 7}]}, contenu: 'ok'}}}); + expect(paroleFindOne).toHaveBeenCalledWith({where: {id: 7}}); + + await afterCreate({params: {data: {parole: 7, contenu: 'ok'}}}); + expect(paroleFindOne).toHaveBeenCalledWith({where: {id: 7}}); + }); }); diff --git a/src/api/commentaire/content-types/commentaire/lifecycles.js b/src/api/commentaire/content-types/commentaire/lifecycles.js index 2ee4b10..a92fb94 100644 --- a/src/api/commentaire/content-types/commentaire/lifecycles.js +++ b/src/api/commentaire/content-types/commentaire/lifecycles.js @@ -2,6 +2,17 @@ const { ApplicationError, NotFoundError } = require('@strapi/utils').errors; +// Le Document Service transforme les relations en { connect: [{id}] } ou +// { set: [{id}] } avant que les hooks bas niveau (beforeCreate/afterCreate) +// ne reçoivent `data` : un id brut n'est plus systématiquement garanti ici. +const idRelasyonAn = valè => { + if (valè == null || typeof valè !== 'object') { + return valè; + } + + return valè.connect?.[0]?.id ?? valè.set?.[0]?.id ?? null; +}; + const jwennUserEpiId = async userId => { if (!userId) { return null; @@ -47,8 +58,8 @@ module.exports = { }, afterCreate: async event => { const {data} = event.params; - const user = await jwennUserEpiId(data.user); - const parole = await jwennParoleEpiId(data.parole); + const user = await jwennUserEpiId(idRelasyonAn(data.user)); + const parole = await jwennParoleEpiId(idRelasyonAn(data.parole)); if (!parole) { throw new NotFoundError('Texte introuvable.');