chore: activer ESLint sur le backend

Installe eslint, ajoute le script lint, modernise le parser
(retrait de babel-eslint obsolète) et applique l'autofix
(points-virgules manquants sur l'ensemble du code, conformément
à la règle "semi" déjà présente dans .eslintrc mais jamais
appliquée faute d'ESLint installé et d'un script pour l'exécuter).
This commit is contained in:
2026-07-04 20:00:51 +04:00
parent 90c048a282
commit 2224c8f3bb
29 changed files with 962 additions and 646 deletions
@@ -1,61 +1,61 @@
import {describe, it, expect, vi, afterEach} from 'vitest'
import {describe, it, expect, vi, afterEach} from 'vitest';
async function loadLifecycles(strapiMock) {
vi.resetModules()
global.strapi = strapiMock
const mod = await import('../lifecycles.js')
return mod
vi.resetModules();
global.strapi = strapiMock;
const mod = await import('../lifecycles.js');
return mod;
}
describe('afterCreate — notification au soumetteur', () => {
afterEach(() => {
delete global.strapi
})
delete global.strapi;
});
it('recherche le user par id (pas par un champ "user" inexistant) et envoie le mail', async () => {
const userFindOne = vi.fn(async ({where}) => {
if (where.id === 5) return {id: 5, username: 'foo', email: 'foo@bar.com'}
return null
})
const emailSend = vi.fn()
if (where.id === 5) return {id: 5, username: 'foo', email: 'foo@bar.com'};
return null;
});
const emailSend = vi.fn();
const strapiMock = {
db: {
query: vi.fn(uid => {
if (uid === 'plugin::users-permissions.user') return {findOne: userFindOne}
return {findOne: vi.fn(async () => null)}
if (uid === 'plugin::users-permissions.user') return {findOne: userFindOne};
return {findOne: vi.fn(async () => null)};
})
},
plugins: {
email: {services: {email: {send: emailSend}}}
}
}
};
const {afterCreate} = await loadLifecycles(strapiMock)
const {afterCreate} = await loadLifecycles(strapiMock);
await afterCreate({params: {data: {titre: 'Titre', user: {id: 5}}}})
await afterCreate({params: {data: {titre: 'Titre', user: {id: 5}}}});
expect(userFindOne).toHaveBeenCalledWith({where: {id: 5}})
expect(emailSend).toHaveBeenCalled()
})
})
expect(userFindOne).toHaveBeenCalledWith({where: {id: 5}});
expect(emailSend).toHaveBeenCalled();
});
});
describe('beforeUpdate — notifications Telegram/Revolt', () => {
const originalEnv = {...process.env}
const axios = require('axios')
const originalPost = axios.post
const originalEnv = {...process.env};
const axios = require('axios');
const originalPost = axios.post;
function buildStrapi(previous) {
const dbQuery = {
findOne: vi.fn(async () => previous),
updateMany: vi.fn()
}
};
return {
db: {query: vi.fn(() => dbQuery)},
plugins: {email: {services: {email: {send: vi.fn()}}}},
log: {error: vi.fn()}
}
};
}
function buildEvent(overrides = {}) {
@@ -64,104 +64,104 @@ describe('beforeUpdate — notifications Telegram/Revolt', () => {
params: {
data: {documentId: 'doc-1', publishedAt: '2026-07-04T00:00:00.000Z', ...overrides}
}
}
};
}
afterEach(() => {
process.env = {...originalEnv}
axios.post = originalPost
delete global.strapi
})
process.env = {...originalEnv};
axios.post = originalPost;
delete global.strapi;
});
it("n'interrompt pas la publication quand Telegram échoue, et encode le message", async () => {
process.env.TELEGRAM_API_TOKEN = 'fake-token'
process.env.TELEGRAM_CHAN_ID = 'fake-chan'
delete process.env.REVOLT_TOKEN
it('n\'interrompt pas la publication quand Telegram échoue, et encode le message', async () => {
process.env.TELEGRAM_API_TOKEN = 'fake-token';
process.env.TELEGRAM_CHAN_ID = 'fake-chan';
delete process.env.REVOLT_TOKEN;
axios.post = vi.fn(async () => {
throw new Error('boom')
})
throw new Error('boom');
});
const previous = {publishedAt: null, slug: 'foo&bar', titre: 'Mon titre', user: null, userAdmin: null, artistes: []}
const strapiMock = buildStrapi(previous)
const previous = {publishedAt: null, slug: 'foo&bar', titre: 'Mon titre', user: null, userAdmin: null, artistes: []};
const strapiMock = buildStrapi(previous);
const {beforeUpdate} = await loadLifecycles(strapiMock)
const {beforeUpdate} = await loadLifecycles(strapiMock);
await beforeUpdate(buildEvent())
await beforeUpdate(buildEvent());
expect(axios.post).toHaveBeenCalledTimes(1)
const [calledUrl] = axios.post.mock.calls[0]
expect(calledUrl).toContain('text=')
expect(calledUrl.split('text=')[1]).not.toContain('&bar')
expect(strapiMock.log.error).toHaveBeenCalledWith(expect.stringContaining('Telegram'))
})
expect(axios.post).toHaveBeenCalledTimes(1);
const [calledUrl] = axios.post.mock.calls[0];
expect(calledUrl).toContain('text=');
expect(calledUrl.split('text=')[1]).not.toContain('&bar');
expect(strapiMock.log.error).toHaveBeenCalledWith(expect.stringContaining('Telegram'));
});
it("n'interrompt pas la publication quand Revolt échoue", async () => {
delete process.env.TELEGRAM_API_TOKEN
process.env.REVOLT_TOKEN = 'fake-token'
process.env.REVOLT_TARGET = 'fake-target'
process.env.REVOLT_BOT_ID = 'fake-bot'
it('n\'interrompt pas la publication quand Revolt échoue', async () => {
delete process.env.TELEGRAM_API_TOKEN;
process.env.REVOLT_TOKEN = 'fake-token';
process.env.REVOLT_TARGET = 'fake-target';
process.env.REVOLT_BOT_ID = 'fake-bot';
axios.post = vi.fn(async () => {
throw new Error('boom')
})
throw new Error('boom');
});
const previous = {publishedAt: null, slug: 'mon-titre', titre: 'Mon titre', user: null, userAdmin: null, artistes: []}
const strapiMock = buildStrapi(previous)
const previous = {publishedAt: null, slug: 'mon-titre', titre: 'Mon titre', user: null, userAdmin: null, artistes: []};
const strapiMock = buildStrapi(previous);
const {beforeUpdate} = await loadLifecycles(strapiMock)
const {beforeUpdate} = await loadLifecycles(strapiMock);
await beforeUpdate(buildEvent())
await beforeUpdate(buildEvent());
expect(axios.post).toHaveBeenCalledTimes(1)
expect(strapiMock.log.error).toHaveBeenCalledWith(expect.stringContaining('Revolt'))
})
})
expect(axios.post).toHaveBeenCalledTimes(1);
expect(strapiMock.log.error).toHaveBeenCalledWith(expect.stringContaining('Revolt'));
});
});
describe('beforeUpdate — createdBy/updatedBy', () => {
afterEach(() => {
delete global.strapi
})
delete global.strapi;
});
it('retire createdBy/updatedBy du payload avant la mise à jour', async () => {
const dbQuery = {findOne: vi.fn(async () => ({publishedAt: null, artistes: []}))}
const strapiMock = {db: {query: vi.fn(() => dbQuery)}}
const dbQuery = {findOne: vi.fn(async () => ({publishedAt: null, artistes: []}))};
const strapiMock = {db: {query: vi.fn(() => dbQuery)}};
const {beforeUpdate} = await loadLifecycles(strapiMock)
const {beforeUpdate} = await loadLifecycles(strapiMock);
const event = {
state: {},
params: {
data: {documentId: 'doc-1', createdBy: 999, updatedBy: 999}
}
}
};
await beforeUpdate(event)
await beforeUpdate(event);
expect(event.params.data.createdBy).toBeUndefined()
expect(event.params.data.updatedBy).toBeUndefined()
})
})
expect(event.params.data.createdBy).toBeUndefined();
expect(event.params.data.updatedBy).toBeUndefined();
});
});
describe('afterUpdate — historique de différence', () => {
afterEach(() => {
delete global.strapi
})
delete global.strapi;
});
it("n'échoue pas quand updatedBy n'est pas peuplé", async () => {
const entityServiceUpdate = vi.fn(async () => {})
it('n\'échoue pas quand updatedBy n\'est pas peuplé', async () => {
const entityServiceUpdate = vi.fn(async () => {});
const strapiMock = {
entityService: {update: entityServiceUpdate}
}
};
const {afterUpdate} = await loadLifecycles(strapiMock)
const {afterUpdate} = await loadLifecycles(strapiMock);
const event = {
result: {id: 1, difference: [], updatedBy: undefined},
state: {diff: {path: 'transcription', jsonDiff: []}}
}
};
await afterUpdate(event)
await afterUpdate(event);
expect(entityServiceUpdate).toHaveBeenCalledWith('api::parole.parole', 1, {
data: {
@@ -173,6 +173,6 @@ describe('afterUpdate — historique de différence', () => {
sources: 'transcription'
}]
}
})
})
})
});
});
});
@@ -1,22 +1,22 @@
'use strict';
const slugify = require('slugify')
const axios = require('axios')
const slugify = require('slugify');
const axios = require('axios');
const utils = require('@strapi/utils')
const { ApplicationError } = utils.errors
const utils = require('@strapi/utils');
const { ApplicationError } = utils.errors;
const TELEGRAM_API_URL = 'https://api.telegram.org'
const TELEGRAM_CHAN_ID = process.env.TELEGRAM_CHAN_ID || null
const TELEGRAM_API_TOKEN = process.env.TELEGRAM_API_TOKEN || null
const MESSAGE_URL = `${TELEGRAM_API_URL}/bot${TELEGRAM_API_TOKEN}/sendMessage?chat_id=${TELEGRAM_CHAN_ID}&parse_mode=html`
const REVOLT_BOT_ID = process.env.REVOLT_BOT_ID || null
const REVOLT_TARGET = process.env.REVOLT_TARGET || null
const REVOLT_TOKEN = process.env.REVOLT_TOKEN || null
const TELEGRAM_API_URL = 'https://api.telegram.org';
const TELEGRAM_CHAN_ID = process.env.TELEGRAM_CHAN_ID || null;
const TELEGRAM_API_TOKEN = process.env.TELEGRAM_API_TOKEN || null;
const MESSAGE_URL = `${TELEGRAM_API_URL}/bot${TELEGRAM_API_TOKEN}/sendMessage?chat_id=${TELEGRAM_CHAN_ID}&parse_mode=html`;
const REVOLT_BOT_ID = process.env.REVOLT_BOT_ID || null;
const REVOLT_TARGET = process.env.REVOLT_TARGET || null;
const REVOLT_TOKEN = process.env.REVOLT_TOKEN || null;
const getSlug = (artiste, parole) => {
return slugify(`${artiste}-${parole}`, {lower: true, remove: /[*#+~.()'"!:@]/g})
}
return slugify(`${artiste}-${parole}`, {lower: true, remove: /[*#+~.()'"!:@]/g});
};
const isSlugExists = async existingSlug => {
const slugs = await strapi.db.query('api::parole.parole').count({
@@ -25,10 +25,10 @@ const isSlugExists = async existingSlug => {
$eq: existingSlug
}
}
})
});
return Boolean(slugs)
}
return Boolean(slugs);
};
const jwennAwtisEpiId = async artistesIds => {
if (!artistesIds || artistesIds.length === 0) {
@@ -42,30 +42,30 @@ const jwennAwtisEpiId = async artistesIds => {
$in: artistesIds.map(id => id)
}
}
})
});
return artistes.map(a => a.alias).join('-')
}
return artistes.map(a => a.alias).join('-');
};
const jwennUserEpiId = async userId => {
if (!userId) {
return null
return null;
}
const user = await strapi.db.query('plugin::users-permissions.user').findOne({
where: {id: userId}
})
});
if (!user) {
throw new ApplicationError('Utilisateur introuvable.')
throw new ApplicationError('Utilisateur introuvable.');
}
return user
}
return user;
};
const jwennUserAdminEpiId = async userAdminId => {
if (!userAdminId) {
return null
return null;
}
const userAdmin = await strapi.db.query('admin::user').findOne({
@@ -83,14 +83,14 @@ const jwennUserAdminEpiId = async userAdminId => {
}
]
}
})
});
return userAdmin
}
return userAdmin;
};
const jwennSuperAdminEpiId = async userAdminId => {
if (!userAdminId) {
return null
return null;
}
const userAdmin = await strapi.db.query('admin::user').findOne({
@@ -108,91 +108,91 @@ const jwennSuperAdminEpiId = async userAdminId => {
}
]
}
})
});
return userAdmin
}
return userAdmin;
};
module.exports = {
beforeCreate: async event => {
let {data} = event.params
let {data} = event.params;
delete data.createdBy
delete data.updatedBy
delete data.createdBy;
delete data.updatedBy;
strapi.service('api::parole.parole').validateParoles(data.titre, data.transcription)
strapi.service('api::parole.parole').validateParoles(data.titre, data.transcription);
let artistesIds = []
let artistesIds = [];
if (data?.artistes?.connect?.length) {
artistesIds = data.artistes.connect.map(a => a.id)
artistesIds = data.artistes.connect.map(a => a.id);
if (data.titre && !data.forceSlug) {
const artiste = await jwennAwtisEpiId(artistesIds)
data.slug = getSlug(artiste, data.titre)
const artiste = await jwennAwtisEpiId(artistesIds);
data.slug = getSlug(artiste, data.titre);
}
const getSlugExistance = await isSlugExists(data.slug)
const getSlugExistance = await isSlugExists(data.slug);
if (getSlugExistance) {
throw new ApplicationError('Un morceau du même artiste existe déjà.')
throw new ApplicationError('Un morceau du même artiste existe déjà.');
}
}
},
beforeUpdate: async event => {
const {state} = event
let {data} = event.params
const {state} = event;
let {data} = event.params;
delete data.createdBy
delete data.updatedBy
delete data.createdBy;
delete data.updatedBy;
const {documentId} = data
const {documentId} = data;
if (data.isNewRelease === true) {
await strapi.db.query('api::parole.parole').updateMany({
where: { isNewRelease: true },
data: { isNewRelease: false },
})
});
}
const previousParoles = await strapi.db.query('api::parole.parole').findOne({
where: {documentId},
populate: {difference: true, artistes: true}
})
});
if (data.transcription && previousParoles.publishedAt) {
const difference = strapi.service('api::parole.parole').parolesDiff(data.titre, previousParoles.transcription, data.transcription)
if (data.transcription && previousParoles.publishedAt) {
const difference = strapi.service('api::parole.parole').parolesDiff(data.titre, previousParoles.transcription, data.transcription);
state.diff = difference
}
state.diff = difference;
}
if(!data.publishedAt && data.titre && data.transcription) {
strapi.service('api::parole.parole').validateParoles(data.titre, data.transcription)
strapi.service('api::parole.parole').validateParoles(data.titre, data.transcription);
if (data.titre && !data.forceSlug) {
let artistes
let artistes;
if (data.artistes.connect.length === 0) {
artistes = previousParoles.artistes.map(a => a.alias).join('-')
artistes = previousParoles.artistes.map(a => a.alias).join('-');
} else {
let artistesIds = []
let artistesIds = [];
artistesIds = data.artistes.connect.map(a => a.id)
artistes = await jwennAwtisEpiId(artistesIds)
artistesIds = data.artistes.connect.map(a => a.id);
artistes = await jwennAwtisEpiId(artistesIds);
}
data.slug = getSlug(artistes, data.titre)
data.slug = getSlug(artistes, data.titre);
}
}
if (data.publishedAt != null) {
const previousData = await strapi.db.query('api::parole.parole').findOne({
where: {documentId}
})
});
const previousPublishedAt = previousData.publishedAt
const currentPublished_at = data.publishedAt
const previousPublishedAt = previousData.publishedAt;
const currentPublished_at = data.publishedAt;
if (currentPublished_at != previousPublishedAt) {
const message = `<b>Nouvelle publication</b> ❤️
\n${process.env.WEBSITE_URL}/paroles/${previousData.slug}`
\n${process.env.WEBSITE_URL}/paroles/${previousData.slug}`;
if (previousData.user) {
strapi.plugins['email'].services.email.send({
from: process.env.SMTP_FROM,
@@ -203,7 +203,7 @@ module.exports = {
Merci pour votre contribution ❤️`,
html: `<p>Le titre que vous avez soumis, <strong>"${previousData.titre}"</strong> a été publié sur le site.</p>
<p>Vous pouvez le trouver à l'adresse <a href="${process.env.WEBSITE_URL}/paroles/${previousData.slug}">${process.env.WEBSITE_URL}/paroles/${previousData.slug}</a>.</p><p>Merci pour votre contribution ❤️</p>`
})
});
}
if (previousData.userAdmin) {
@@ -216,66 +216,66 @@ module.exports = {
Merci pour votre contribution ❤️`,
html: `<p>Le titre que vous avez soumis, <strong>"${previousData.titre}"</strong> a été publié sur le site.</p>
<p>Vous pouvez le trouver à l'adresse <a href="${process.env.WEBSITE_URL}/paroles/${previousData.slug}">${process.env.WEBSITE_URL}/paroles/${previousData.slug}</a>.</p><p>Merci pour votre contribution ❤️</p>`
})
});
}
if (TELEGRAM_API_TOKEN) {
try {
await axios.post(`${MESSAGE_URL}&text=${encodeURIComponent(message)}`)
await axios.post(`${MESSAGE_URL}&text=${encodeURIComponent(message)}`);
} catch (err) {
strapi.log.error(`Notification Telegram : ${err.message}`)
strapi.log.error(`Notification Telegram : ${err.message}`);
}
}
if (REVOLT_TOKEN && REVOLT_TARGET && REVOLT_BOT_ID) {
const revoltMessage = `Nouvelle publication
\n${process.env.WEBSITE_URL}/paroles/${previousData.slug}`
\n${process.env.WEBSITE_URL}/paroles/${previousData.slug}`;
const targetChannel = REVOLT_TARGET
const botToken = REVOLT_TOKEN
const url = `https://api.revolt.chat/channels/${targetChannel}/messages`
const targetChannel = REVOLT_TARGET;
const botToken = REVOLT_TOKEN;
const url = `https://api.revolt.chat/channels/${targetChannel}/messages`;
const config = {
headers: {
'X-Bot-Token': botToken,
'Content-Type': 'application/json'
}
}
};
try {
await axios.post(url, {content: revoltMessage}, config)
await axios.post(url, {content: revoltMessage}, config);
} catch (err) {
strapi.log.error(`Notification Revolt : ${err.message}`)
strapi.log.error(`Notification Revolt : ${err.message}`);
}
}
}
}
},
afterUpdate: async event => {
const {result, state} = event
const {result, state} = event;
if (state.diff) {
await strapi.entityService.update('api::parole.parole', result.id, {
data: {
difference: [
...result.difference,
{
admin_user: result.updatedBy?.id ?? null,
paroles: state.diff.path,
jsonDiff: state.diff.jsonDiff,
date: new Date(),
sources: 'transcription'
}]
...result.difference,
{
admin_user: result.updatedBy?.id ?? null,
paroles: state.diff.path,
jsonDiff: state.diff.jsonDiff,
date: new Date(),
sources: 'transcription'
}]
}
})
});
}
},
afterCreate: async event => {
const {data} = event.params
const user = await jwennUserEpiId(data?.user?.id)
const userAdmin = await jwennUserAdminEpiId(data?.createdBy)
const superAdmin = await jwennSuperAdminEpiId(data?.createdBy)
const traductionsId = data?.traductions?.id
const {data} = event.params;
const user = await jwennUserEpiId(data?.user?.id);
const userAdmin = await jwennUserAdminEpiId(data?.createdBy);
const superAdmin = await jwennSuperAdminEpiId(data?.createdBy);
const traductionsId = data?.traductions?.id;
if (traductionsId) {
const result = await strapi.db.query('api::parole.parole').findOne({
@@ -287,15 +287,15 @@ module.exports = {
}
},
populate: {traductions: true, artistes: true}
})
});
if (superAdmin && data.traductionAuto && result.traductions.francais && (!result.traductions.anglais || !result.traductions.espagnol || !result.traductions.allemand || !result.traductions.italien)) {
const traductions = await strapi.service('api::parole.parole').translateLyrics(result.traductions.francais)
const traductions = await strapi.service('api::parole.parole').translateLyrics(result.traductions.francais);
await strapi.entityService.update('api::parole.parole', result.id, {
data: {
traductions
}
})
});
}
}
@@ -306,7 +306,7 @@ module.exports = {
subject: `Nouveau texte de ${user.username} : "${data.titre}" (site)`,
text: `Le titre "${data.titre}" a été soumis depuis le site.`,
html: `Le titre <strong>"${data.titre}"</strong> a été soumis depuis le site.`
})
});
}
if (userAdmin) {
@@ -316,7 +316,7 @@ module.exports = {
subject: `Nouveau texte de ${userAdmin.firstname} : "${data.titre}" (site)`,
text: `Le titre "${data.titre}" a été soumis depuis le site.`,
html: `Le titre <strong>"${data.titre}"</strong> a été soumis depuis le site.`
})
});
}
}
}
};
@@ -1,20 +1,20 @@
import {describe, it, expect, vi} from 'vitest'
import {describe, it, expect, vi} from 'vitest';
const {default: createController} = await import('../parole.js')
const {default: createController} = await import('../parole.js');
function buildStrapi({dbUser, artiste}) {
const paroleDocuments = {
findMany: vi.fn(async () => []),
create: vi.fn(async ({data}) => ({id: 42, ...data})),
update: vi.fn(async ({data}) => ({id: 42, ...data}))
}
};
const userDocuments = {
findOne: vi.fn(async () => dbUser),
update: vi.fn(async () => {})
}
};
const artisteDocuments = {
findOne: vi.fn(async () => artiste)
}
};
const strapi = {
contentType: vi.fn(() => ({uid: 'api::parole.parole', kind: 'collectionType'})),
@@ -23,14 +23,14 @@ function buildStrapi({dbUser, artiste}) {
translateLyrics: vi.fn()
})),
documents: vi.fn(uid => {
if (uid === 'plugin::users-permissions.user') return userDocuments
if (uid === 'api::artiste.artiste') return artisteDocuments
if (uid === 'api::parole.parole') return paroleDocuments
throw new Error(`unexpected uid: ${uid}`)
if (uid === 'plugin::users-permissions.user') return userDocuments;
if (uid === 'api::artiste.artiste') return artisteDocuments;
if (uid === 'api::parole.parole') return paroleDocuments;
throw new Error(`unexpected uid: ${uid}`);
})
}
};
return {strapi, paroleDocuments, userDocuments, artisteDocuments}
return {strapi, paroleDocuments, userDocuments, artisteDocuments};
}
function buildCtx(data) {
@@ -41,11 +41,11 @@ function buildCtx(data) {
},
badRequest: vi.fn(),
notFound: vi.fn()
}
};
}
const dbUser = {id: 1, documentId: 'user-doc-1', username: 'foo', email: 'foo@bar.com'}
const artiste = {id: 9, documentId: 'artiste-doc-1'}
const dbUser = {id: 1, documentId: 'user-doc-1', username: 'foo', email: 'foo@bar.com'};
const artiste = {id: 9, documentId: 'artiste-doc-1'};
function buildData(overrides = {}) {
return {
@@ -54,77 +54,77 @@ function buildData(overrides = {}) {
user: {...dbUser},
artistes: [{documentId: 'artiste-doc-1'}],
...overrides
}
};
}
describe('parole.findOne', () => {
it('interroge avec le documentId venant de ctx.params.id, pas avec ctx lui-même', async () => {
const paroleDocuments = {
findOne: vi.fn(async ({documentId}) => ({id: 1, documentId, titre: 'Test'}))
}
};
const strapi = {
contentType: vi.fn(() => ({uid: 'api::parole.parole', kind: 'collectionType'})),
documents: vi.fn(uid => {
if (uid === 'api::parole.parole') return paroleDocuments
throw new Error(`unexpected uid: ${uid}`)
if (uid === 'api::parole.parole') return paroleDocuments;
throw new Error(`unexpected uid: ${uid}`);
})
}
const controller = createController({strapi})
const ctx = {params: {id: 'doc-123'}}
};
const controller = createController({strapi});
const ctx = {params: {id: 'doc-123'}};
const result = await controller.findOne(ctx)
const result = await controller.findOne(ctx);
expect(paroleDocuments.findOne).toHaveBeenCalledWith({
documentId: 'doc-123',
populate: ['artistes']
})
expect(result).toEqual({id: 1, documentId: 'doc-123', titre: 'Test'})
})
})
});
expect(result).toEqual({id: 1, documentId: 'doc-123', titre: 'Test'});
});
});
describe('parole.create', () => {
it('crée la parole quand le user et l\'artiste existent', async () => {
const {strapi, paroleDocuments} = buildStrapi({dbUser, artiste})
const controller = createController({strapi})
const ctx = buildCtx(buildData())
const {strapi, paroleDocuments} = buildStrapi({dbUser, artiste});
const controller = createController({strapi});
const ctx = buildCtx(buildData());
await controller.create(ctx)
await controller.create(ctx);
expect(paroleDocuments.create).toHaveBeenCalled()
})
expect(paroleDocuments.create).toHaveBeenCalled();
});
it('refuse sans planter quand data.user est absent', async () => {
const {strapi, userDocuments} = buildStrapi({dbUser, artiste})
const controller = createController({strapi})
const ctx = buildCtx(buildData({user: undefined}))
const {strapi, userDocuments} = buildStrapi({dbUser, artiste});
const controller = createController({strapi});
const ctx = buildCtx(buildData({user: undefined}));
await controller.create(ctx)
await controller.create(ctx);
expect(ctx.badRequest).toHaveBeenCalled()
expect(userDocuments.findOne).not.toHaveBeenCalled()
})
expect(ctx.badRequest).toHaveBeenCalled();
expect(userDocuments.findOne).not.toHaveBeenCalled();
});
it('refuse sans planter quand data.artistes est vide', async () => {
const {strapi, artisteDocuments} = buildStrapi({dbUser, artiste})
const controller = createController({strapi})
const ctx = buildCtx(buildData({artistes: []}))
const {strapi, artisteDocuments} = buildStrapi({dbUser, artiste});
const controller = createController({strapi});
const ctx = buildCtx(buildData({artistes: []}));
await controller.create(ctx)
await controller.create(ctx);
expect(ctx.badRequest).toHaveBeenCalled()
expect(artisteDocuments.findOne).not.toHaveBeenCalled()
})
expect(ctx.badRequest).toHaveBeenCalled();
expect(artisteDocuments.findOne).not.toHaveBeenCalled();
});
it('ignore les champs non autorisés du payload (mass assignment)', async () => {
const {strapi, paroleDocuments} = buildStrapi({dbUser, artiste})
const controller = createController({strapi})
const {strapi, paroleDocuments} = buildStrapi({dbUser, artiste});
const controller = createController({strapi});
const ctx = buildCtx(buildData({
userAdmin: {id: 999},
isNewRelease: true,
difference: [{fake: true}]
}))
}));
await controller.create(ctx)
await controller.create(ctx);
expect(paroleDocuments.create).toHaveBeenCalledWith({
data: {
@@ -135,14 +135,14 @@ describe('parole.create', () => {
artistes: [artiste.id],
user: dbUser.id
}
})
})
})
});
});
});
describe('parole.update', () => {
it('ignore les champs non autorisés du payload (mass assignment)', async () => {
const {strapi, paroleDocuments} = buildStrapi({dbUser, artiste})
const controller = createController({strapi})
const {strapi, paroleDocuments} = buildStrapi({dbUser, artiste});
const controller = createController({strapi});
const ctx = buildCtx({
documentId: 'doc-1',
titre: 'Nouveau titre',
@@ -152,9 +152,9 @@ describe('parole.update', () => {
artistes: [9],
userAdmin: {id: 999},
user: {id: 999}
})
});
await controller.update(ctx)
await controller.update(ctx);
expect(paroleDocuments.update).toHaveBeenCalledWith({
documentId: 'doc-1',
@@ -165,6 +165,6 @@ describe('parole.update', () => {
traductionAuto: true,
artistes: [9]
}
})
})
})
});
});
});
+39 -39
View File
@@ -2,29 +2,29 @@
const { createCoreController } = require('@strapi/strapi').factories;
const VALID_LANGS = new Set(['fr', 'en', 'es', 'de', 'it'])
const VALID_LANGS = new Set(['fr', 'en', 'es', 'de', 'it']);
module.exports = createCoreController('api::parole.parole', ({strapi}) => ({
async export(ctx) {
const { type = 'pairs', lang, format = 'jsonl' } = ctx.query
const { type = 'pairs', lang, format = 'jsonl' } = ctx.query;
const langs = lang
? lang.split(',').map(l => l.trim()).filter(l => VALID_LANGS.has(l))
: null
: null;
if (lang && (!langs || langs.length === 0)) {
return ctx.badRequest('Langue(s) invalide(s). Valeurs acceptées : fr, en, es, de, it.')
return ctx.badRequest('Langue(s) invalide(s). Valeurs acceptées : fr, en, es, de, it.');
}
if (!['pairs', 'instruct'].includes(type)) {
return ctx.badRequest('type invalide. Valeurs acceptées : pairs, instruct.')
return ctx.badRequest('type invalide. Valeurs acceptées : pairs, instruct.');
}
const paroles = await strapi.service('api::parole.parole').fetchAllParoles()
const { metadata, pairs } = strapi.service('api::parole.parole').buildExport(paroles, type, langs)
const paroles = await strapi.service('api::parole.parole').fetchAllParoles();
const { metadata, pairs } = strapi.service('api::parole.parole').buildExport(paroles, type, langs);
if (format === 'json') {
return ctx.send({ metadata, data: pairs })
return ctx.send({ metadata, data: pairs });
}
// JSONL : première ligne = métadonnées, suivies des exemples d'entraînement.
@@ -32,30 +32,30 @@ module.exports = createCoreController('api::parole.parole', ({strapi}) => ({
const lines = [
JSON.stringify({ _metadata: true, ...metadata }),
...pairs.map(p => JSON.stringify(p)),
]
];
ctx.set('Content-Type', 'application/x-ndjson')
ctx.set('Content-Disposition', `attachment; filename="pawol-nu-export-${Date.now()}.jsonl"`)
ctx.body = lines.join('\n')
ctx.set('Content-Type', 'application/x-ndjson');
ctx.set('Content-Disposition', `attachment; filename="pawol-nu-export-${Date.now()}.jsonl"`);
ctx.body = lines.join('\n');
},
async bulkTranslate(ctx) {
const result = await strapi.service('api::parole.parole').bulkTranslateMissing()
return ctx.send(result)
const result = await strapi.service('api::parole.parole').bulkTranslateMissing();
return ctx.send(result);
},
async findOne(ctx) {
const {id: documentId} = ctx.params
const {id: documentId} = ctx.params;
const parole = await strapi.documents('api::parole.parole').findOne({
documentId,
populate: ['artistes']
})
});
return parole
return parole;
},
async update(ctx) {
const {body} = ctx.request
const {data} = body
const {body} = ctx.request;
const {data} = body;
const updatedParole = await strapi.documents('api::parole.parole').update({
documentId: data.documentId,
@@ -67,38 +67,38 @@ module.exports = createCoreController('api::parole.parole', ({strapi}) => ({
traductionAuto: data.traductionAuto,
artistes: data.artistes
}
})
});
return updatedParole
return updatedParole;
},
async create(ctx) {
const {body} = ctx.request
const {data} = body
const {body} = ctx.request;
const {data} = body;
if (!data?.user?.documentId || !data?.artistes?.[0]?.documentId) {
return ctx.badRequest('Informations manquantes.')
return ctx.badRequest('Informations manquantes.');
}
strapi.service('api::parole.parole').validateParoles(data.titre, data.transcription)
strapi.service('api::parole.parole').validateParoles(data.titre, data.transcription);
const user = await strapi.documents('plugin::users-permissions.user').findOne({
documentId: body.data.user.documentId
})
});
if (!user) {
return ctx.notFound('Utilisateur introuvable.')
return ctx.notFound('Utilisateur introuvable.');
}
if (user.id !== data.user.id || user.username !== data.user.username || user.email !== data.user.email) {
return ctx.badRequest('Informations non valides.')
return ctx.badRequest('Informations non valides.');
}
const artiste = await strapi.documents('api::artiste.artiste').findOne({
documentId: data.artistes[0].documentId
})
});
if (!artiste) {
return ctx.notFound('Artiste introuvable.')
return ctx.notFound('Artiste introuvable.');
}
const currentUserParole = await strapi.documents('api::parole.parole').findMany({
@@ -113,12 +113,12 @@ module.exports = createCoreController('api::parole.parole', ({strapi}) => ({
$eq: null
}
}
})
});
if (user && user.canAutoTranslate && data.traductionAuto && data.traductions.francais && (!data.traductions.anglais || !data.traductions.espagnol || !data.traductions.allemand || !data.traductions.italien)) {
const translated = await strapi.service('api::parole.parole').translateLyrics(data.traductions.francais)
data.traductions = translated
const translated = await strapi.service('api::parole.parole').translateLyrics(data.traductions.francais);
data.traductions = translated;
}
const newParole = await strapi.documents('api::parole.parole').create({
@@ -130,10 +130,10 @@ module.exports = createCoreController('api::parole.parole', ({strapi}) => ({
artistes: [artiste.id],
user: user.id
}
})
});
const parolesIds = currentUserParole.map(({id}) => id)
parolesIds.push(newParole.id)
const parolesIds = currentUserParole.map(({id}) => id);
parolesIds.push(newParole.id);
await strapi.documents('plugin::users-permissions.user').update({
documentId: user.documentId,
@@ -141,8 +141,8 @@ module.exports = createCoreController('api::parole.parole', ({strapi}) => ({
data: {
paroles: parolesIds
}
})
});
return newParole
return newParole;
}
}))
}));
@@ -1,19 +1,19 @@
import {describe, it, expect} from 'vitest'
import isApiToken from '../is-api-token.js'
import {describe, it, expect} from 'vitest';
import isApiToken from '../is-api-token.js';
describe('is-api-token policy', () => {
it('autorise une requête authentifiée par token API', () => {
const ctx = {state: {auth: {strategy: {name: 'api-token'}}}}
expect(isApiToken(ctx)).toBe(true)
})
const ctx = {state: {auth: {strategy: {name: 'api-token'}}}};
expect(isApiToken(ctx)).toBe(true);
});
it('refuse une requête authentifiée autrement (ex: JWT utilisateur)', () => {
const ctx = {state: {auth: {strategy: {name: 'users-permissions'}}}}
expect(isApiToken(ctx)).toBe(false)
})
const ctx = {state: {auth: {strategy: {name: 'users-permissions'}}}};
expect(isApiToken(ctx)).toBe(false);
});
it('refuse une requête non authentifiée', () => {
const ctx = {state: {}}
expect(isApiToken(ctx)).toBe(false)
})
})
const ctx = {state: {}};
expect(isApiToken(ctx)).toBe(false);
});
});
+2 -2
View File
@@ -1,5 +1,5 @@
'use strict';
module.exports = policyContext => {
return policyContext.state?.auth?.strategy?.name === 'api-token'
}
return policyContext.state?.auth?.strategy?.name === 'api-token';
};
+1 -1
View File
@@ -14,4 +14,4 @@ module.exports = createCoreRouter('api::parole.parole', {
policies: [{name: 'global::is-document-owner', config: {uid: 'api::parole.parole'}}]
}
}
})
});
@@ -1,60 +1,60 @@
import {describe, it, expect, vi, afterEach} from 'vitest'
import {describe, it, expect, vi, afterEach} from 'vitest';
const {default: createService} = await import('../parole.js')
const {default: createService} = await import('../parole.js');
function fakeDeeplResponse(text) {
return {
ok: true,
json: async () => ({translations: [{text}]})
}
};
}
describe('Translator (DeepL)', () => {
const originalFetch = global.fetch
const originalFetch = global.fetch;
afterEach(() => {
global.fetch = originalFetch
vi.restoreAllMocks()
})
global.fetch = originalFetch;
vi.restoreAllMocks();
});
it('attache un timeout à la requête DeepL', async () => {
global.fetch = vi.fn(async () => fakeDeeplResponse('hello'))
global.fetch = vi.fn(async () => fakeDeeplResponse('hello'));
const strapi = {contentType: vi.fn(() => ({uid: 'api::parole.parole', kind: 'collectionType'}))}
const service = createService({strapi})
await service.translate('FR', 'EN', 'bonjour')
const strapi = {contentType: vi.fn(() => ({uid: 'api::parole.parole', kind: 'collectionType'}))};
const service = createService({strapi});
await service.translate('FR', 'EN', 'bonjour');
const [, options] = global.fetch.mock.calls[0]
expect(options.signal).toBeInstanceOf(AbortSignal)
})
})
const [, options] = global.fetch.mock.calls[0];
expect(options.signal).toBeInstanceOf(AbortSignal);
});
});
describe('translateLyrics', () => {
const originalFetch = global.fetch
const originalFetch = global.fetch;
afterEach(() => {
global.fetch = originalFetch
vi.restoreAllMocks()
})
global.fetch = originalFetch;
vi.restoreAllMocks();
});
it('continue les autres langues quand une traduction DeepL échoue', async () => {
global.fetch = vi.fn(async (_url, options) => {
const {target_lang: target} = JSON.parse(options.body)
const {target_lang: target} = JSON.parse(options.body);
if (target === 'ES') {
return {ok: false, status: 500, text: async () => 'boom'}
return {ok: false, status: 500, text: async () => 'boom'};
}
return fakeDeeplResponse(`traduit-${target}`)
})
return fakeDeeplResponse(`traduit-${target}`);
});
const strapi = {
contentType: vi.fn(() => ({uid: 'api::parole.parole', kind: 'collectionType'})),
log: {error: vi.fn()}
}
const service = createService({strapi})
const result = await service.translateLyrics('Bonjour le monde')
};
const service = createService({strapi});
const result = await service.translateLyrics('Bonjour le monde');
expect(result.anglais).toContain('traduit-EN')
expect(result.espagnol).toBeUndefined()
})
})
expect(result.anglais).toContain('traduit-EN');
expect(result.espagnol).toBeUndefined();
});
});