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:
@@ -1,66 +1,66 @@
|
||||
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('artiste afterUpdate — cascade de renommage des slugs', () => {
|
||||
afterEach(() => {
|
||||
delete global.strapi
|
||||
})
|
||||
delete global.strapi;
|
||||
});
|
||||
|
||||
it("renomme le slug des paroles de l'artiste quand son alias change", async () => {
|
||||
it('renomme le slug des paroles de l\'artiste quand son alias change', async () => {
|
||||
const artisteFindOne = vi.fn(async () => ({
|
||||
id: 5,
|
||||
paroles: [{id: 10}, {id: 11}]
|
||||
}))
|
||||
}));
|
||||
const paroleFindMany = vi.fn(async () => [
|
||||
{id: 10, titre: 'Titre 1', slug: 'ancien-alias-titre-1', artistes: [{alias: 'nouvel-alias'}]},
|
||||
{id: 11, titre: 'Titre 2', slug: 'nouvel-alias-titre-2', artistes: [{alias: 'nouvel-alias'}]}
|
||||
])
|
||||
const paroleUpdate = vi.fn(async () => {})
|
||||
]);
|
||||
const paroleUpdate = vi.fn(async () => {});
|
||||
|
||||
const strapiMock = {
|
||||
db: {
|
||||
query: vi.fn(uid => {
|
||||
if (uid === 'api::artiste.artiste') return {findOne: artisteFindOne}
|
||||
if (uid === 'api::parole.parole') return {findMany: paroleFindMany, update: paroleUpdate}
|
||||
throw new Error(`unexpected uid: ${uid}`)
|
||||
if (uid === 'api::artiste.artiste') return {findOne: artisteFindOne};
|
||||
if (uid === 'api::parole.parole') return {findMany: paroleFindMany, update: paroleUpdate};
|
||||
throw new Error(`unexpected uid: ${uid}`);
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const {afterUpdate} = await loadLifecycles(strapiMock)
|
||||
const {afterUpdate} = await loadLifecycles(strapiMock);
|
||||
|
||||
await afterUpdate({result: {id: 5}})
|
||||
await afterUpdate({result: {id: 5}});
|
||||
|
||||
expect(artisteFindOne).toHaveBeenCalledWith({where: {id: 5}, populate: ['paroles']})
|
||||
expect(paroleFindMany).toHaveBeenCalledWith({where: {id: {$in: [10, 11]}}, populate: ['artistes']})
|
||||
expect(paroleUpdate).toHaveBeenCalledTimes(1)
|
||||
expect(paroleUpdate).toHaveBeenCalledWith({where: {id: 10}, data: {slug: 'nouvel-alias-titre-1'}})
|
||||
})
|
||||
expect(artisteFindOne).toHaveBeenCalledWith({where: {id: 5}, populate: ['paroles']});
|
||||
expect(paroleFindMany).toHaveBeenCalledWith({where: {id: {$in: [10, 11]}}, populate: ['artistes']});
|
||||
expect(paroleUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(paroleUpdate).toHaveBeenCalledWith({where: {id: 10}, data: {slug: 'nouvel-alias-titre-1'}});
|
||||
});
|
||||
|
||||
it("ne fait rien quand l'artiste n'a aucune parole", async () => {
|
||||
const artisteFindOne = vi.fn(async () => ({id: 5, paroles: []}))
|
||||
const paroleFindMany = vi.fn()
|
||||
it('ne fait rien quand l\'artiste n\'a aucune parole', async () => {
|
||||
const artisteFindOne = vi.fn(async () => ({id: 5, paroles: []}));
|
||||
const paroleFindMany = vi.fn();
|
||||
|
||||
const strapiMock = {
|
||||
db: {
|
||||
query: vi.fn(uid => {
|
||||
if (uid === 'api::artiste.artiste') return {findOne: artisteFindOne}
|
||||
if (uid === 'api::parole.parole') return {findMany: paroleFindMany}
|
||||
throw new Error(`unexpected uid: ${uid}`)
|
||||
if (uid === 'api::artiste.artiste') return {findOne: artisteFindOne};
|
||||
if (uid === 'api::parole.parole') return {findMany: paroleFindMany};
|
||||
throw new Error(`unexpected uid: ${uid}`);
|
||||
})
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const {afterUpdate} = await loadLifecycles(strapiMock)
|
||||
const {afterUpdate} = await loadLifecycles(strapiMock);
|
||||
|
||||
await afterUpdate({result: {id: 5}})
|
||||
await afterUpdate({result: {id: 5}});
|
||||
|
||||
expect(paroleFindMany).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
expect(paroleFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
const { ApplicationError } = require("@strapi/utils").errors
|
||||
const slugify = require('slugify')
|
||||
const { ApplicationError } = require('@strapi/utils').errors;
|
||||
const slugify = require('slugify');
|
||||
|
||||
const jwennTeksEpiId = async ids => {
|
||||
const paroles = await strapi.db.query('api::parole.parole').findMany({
|
||||
where: {id: {$in: ids}},
|
||||
populate: ['artistes']
|
||||
})
|
||||
return paroles
|
||||
}
|
||||
});
|
||||
return paroles;
|
||||
};
|
||||
|
||||
const jwennAwtisEpiId = async id => {
|
||||
const artiste = await strapi.db.query('api::artiste.artiste').findOne({
|
||||
where: {id},
|
||||
populate: ['paroles']
|
||||
})
|
||||
return artiste
|
||||
}
|
||||
});
|
||||
return artiste;
|
||||
};
|
||||
|
||||
const validateArtiste = alias => {
|
||||
if (!alias || alias.trim().length === 0) {
|
||||
throw new ApplicationError('Champ obligatoire. Veuillez choisir un alias.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
beforeUpdate: async event => {
|
||||
let {data} = event.params
|
||||
let {data} = event.params;
|
||||
|
||||
if(!data.publishedAt) {
|
||||
validateArtiste(data.alias)
|
||||
validateArtiste(data.alias);
|
||||
|
||||
if (!data.slug || data.slug !== slugify(data.alias, {lower: true, remove: /[*#+~.()'"!:@]/g})) {
|
||||
data.slug = slugify(data.alias, {lower: true, remove: /[*#+~.()'"!:@]/g})
|
||||
data.slug = slugify(data.alias, {lower: true, remove: /[*#+~.()'"!:@]/g});
|
||||
}
|
||||
}
|
||||
},
|
||||
beforeCreate: async event => {
|
||||
let {data} = event.params
|
||||
let {data} = event.params;
|
||||
|
||||
validateArtiste(data.alias)
|
||||
validateArtiste(data.alias);
|
||||
|
||||
data.slug = slugify(data.alias, {lower: true, remove: /[*#+~.()'"!:@]/g})
|
||||
data.slug = slugify(data.alias, {lower: true, remove: /[*#+~.()'"!:@]/g});
|
||||
},
|
||||
afterUpdate: async event => {
|
||||
const {result} = event
|
||||
const artiste = await jwennAwtisEpiId(result.id)
|
||||
const {result} = event;
|
||||
const artiste = await jwennAwtisEpiId(result.id);
|
||||
|
||||
if (artiste.paroles && artiste.paroles.length >= 1) {
|
||||
const paroleIds = artiste.paroles.map(({id}) => id)
|
||||
const paroles = await jwennTeksEpiId(paroleIds)
|
||||
const paroleIds = artiste.paroles.map(({id}) => id);
|
||||
const paroles = await jwennTeksEpiId(paroleIds);
|
||||
await Promise.all(paroles.map(async t => {
|
||||
const {id, titre, slug, artistes} = t
|
||||
const alias = artistes.map(a => a.alias).join('-')
|
||||
const slugUpdated = slugify(`${alias}-${titre}`, {lower: true, remove: /[*#+~.()'"!:@]/g})
|
||||
const {id, titre, slug, artistes} = t;
|
||||
const alias = artistes.map(a => a.alias).join('-');
|
||||
const slugUpdated = slugify(`${alias}-${titre}`, {lower: true, remove: /[*#+~.()'"!:@]/g});
|
||||
|
||||
if (slug !== slugUpdated) {
|
||||
await strapi.db.query('api::parole.parole').update({
|
||||
@@ -62,9 +62,9 @@ module.exports = {
|
||||
data: {
|
||||
slug: slugUpdated
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}))
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import {describe, it, expect, vi} from 'vitest'
|
||||
import {describe, it, expect, vi} from 'vitest';
|
||||
|
||||
const {default: createController} = await import('../artiste.js')
|
||||
const {default: createController} = await import('../artiste.js');
|
||||
|
||||
function buildStrapi({dbUser, existingArtiste = null}) {
|
||||
const dbQuery = {
|
||||
findOne: vi.fn(async () => existingArtiste)
|
||||
}
|
||||
};
|
||||
const artisteDocuments = {
|
||||
create: vi.fn(async ({data}) => ({id: 42, ...data}))
|
||||
}
|
||||
};
|
||||
const userDocuments = {
|
||||
findOne: vi.fn(async () => dbUser)
|
||||
}
|
||||
};
|
||||
|
||||
const strapi = {
|
||||
contentType: vi.fn(() => ({uid: 'api::artiste.artiste', kind: 'collectionType'})),
|
||||
@@ -19,13 +19,13 @@ function buildStrapi({dbUser, existingArtiste = null}) {
|
||||
query: vi.fn(() => dbQuery)
|
||||
},
|
||||
documents: vi.fn(uid => {
|
||||
if (uid === 'plugin::users-permissions.user') return userDocuments
|
||||
if (uid === 'api::artiste.artiste') return artisteDocuments
|
||||
throw new Error(`unexpected uid: ${uid}`)
|
||||
if (uid === 'plugin::users-permissions.user') return userDocuments;
|
||||
if (uid === 'api::artiste.artiste') return artisteDocuments;
|
||||
throw new Error(`unexpected uid: ${uid}`);
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
return {strapi, artisteDocuments}
|
||||
return {strapi, artisteDocuments};
|
||||
}
|
||||
|
||||
function buildCtx(data) {
|
||||
@@ -36,56 +36,56 @@ function buildCtx(data) {
|
||||
},
|
||||
badRequest: vi.fn(),
|
||||
notFound: vi.fn()
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const dbUser = {id: 1, documentId: 'user-doc-1', username: 'foo', email: 'foo@bar.com'}
|
||||
const dbUser = {id: 1, documentId: 'user-doc-1', username: 'foo', email: 'foo@bar.com'};
|
||||
|
||||
function buildData(overrides = {}) {
|
||||
return {
|
||||
alias: 'Test Artist',
|
||||
user: {...dbUser},
|
||||
...overrides
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('artiste.create', () => {
|
||||
it('crée l\'artiste quand le user existe et que l\'alias est nouveau', async () => {
|
||||
const {strapi, artisteDocuments} = buildStrapi({dbUser})
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData())
|
||||
const {strapi, artisteDocuments} = buildStrapi({dbUser});
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData());
|
||||
|
||||
await controller.create(ctx)
|
||||
await controller.create(ctx);
|
||||
|
||||
expect(artisteDocuments.create).toHaveBeenCalled()
|
||||
})
|
||||
expect(artisteDocuments.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuse sans planter quand data.user est absent', async () => {
|
||||
const {strapi} = buildStrapi({dbUser})
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData({user: undefined}))
|
||||
const {strapi} = buildStrapi({dbUser});
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData({user: undefined}));
|
||||
|
||||
await controller.create(ctx)
|
||||
await controller.create(ctx);
|
||||
|
||||
expect(ctx.badRequest).toHaveBeenCalled()
|
||||
expect(strapi.documents).not.toHaveBeenCalled()
|
||||
})
|
||||
expect(ctx.badRequest).toHaveBeenCalled();
|
||||
expect(strapi.documents).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignore les champs non autorisés du payload (mass assignment)', async () => {
|
||||
const {strapi, artisteDocuments} = buildStrapi({dbUser})
|
||||
const controller = createController({strapi})
|
||||
const {strapi, artisteDocuments} = buildStrapi({dbUser});
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData({
|
||||
isExclusiveArtist: true,
|
||||
userAdmin: {id: 999}
|
||||
}))
|
||||
}));
|
||||
|
||||
await controller.create(ctx)
|
||||
await controller.create(ctx);
|
||||
|
||||
expect(artisteDocuments.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
alias: 'Test Artist',
|
||||
user: dbUser.id
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
const { createCoreController } = require('@strapi/strapi').factories;
|
||||
const slugify = require('slugify')
|
||||
const slugify = require('slugify');
|
||||
|
||||
const getSlug = text => {
|
||||
return slugify(text, {lower: true, remove: /[*#+~.()'"!:@]/g})
|
||||
}
|
||||
return slugify(text, {lower: true, remove: /[*#+~.()'"!:@]/g});
|
||||
};
|
||||
|
||||
module.exports = createCoreController('api::artiste.artiste', ({strapi}) => ({
|
||||
async create(ctx) {
|
||||
const {body} = ctx.request
|
||||
let {data} = body
|
||||
const {body} = ctx.request;
|
||||
let {data} = body;
|
||||
|
||||
if (!data?.user?.documentId) {
|
||||
return ctx.badRequest('Informations manquantes.')
|
||||
return ctx.badRequest('Informations manquantes.');
|
||||
}
|
||||
|
||||
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.db.query('api::artiste.artiste').findOne({
|
||||
where: {slug: getSlug(data.alias)}
|
||||
})
|
||||
});
|
||||
|
||||
if (artiste) {
|
||||
return artiste
|
||||
return artiste;
|
||||
} else {
|
||||
const newArtiste = await strapi.documents('api::artiste.artiste').create({
|
||||
data: {
|
||||
alias: data.alias,
|
||||
user: user.id
|
||||
}
|
||||
})
|
||||
return newArtiste
|
||||
});
|
||||
return newArtiste;
|
||||
}
|
||||
}
|
||||
|
||||
}))
|
||||
}));
|
||||
|
||||
@@ -14,4 +14,4 @@ module.exports = createCoreRouter('api::artiste.artiste', {
|
||||
policies: [{name: 'global::is-document-owner', config: {uid: 'api::artiste.artiste'}}]
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
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('commentaire afterCreate — notification email', () => {
|
||||
afterEach(() => {
|
||||
delete global.strapi
|
||||
})
|
||||
delete global.strapi;
|
||||
});
|
||||
|
||||
it("envoie le contenu en texte brut, jamais comme HTML non échappé", async () => {
|
||||
const emailSend = vi.fn()
|
||||
it('envoie le contenu en texte brut, jamais comme HTML non échappé', async () => {
|
||||
const emailSend = vi.fn();
|
||||
const strapiMock = {
|
||||
db: {
|
||||
query: vi.fn(uid => {
|
||||
if (uid === 'plugin::users-permissions.user') return {findOne: vi.fn(async () => ({id: 1, username: 'foo'}))}
|
||||
if (uid === 'api::parole.parole') return {findOne: vi.fn(async () => ({id: 7, titre: 'Mon titre'}))}
|
||||
throw new Error(`unexpected uid: ${uid}`)
|
||||
if (uid === 'plugin::users-permissions.user') return {findOne: vi.fn(async () => ({id: 1, username: 'foo'}))};
|
||||
if (uid === 'api::parole.parole') return {findOne: vi.fn(async () => ({id: 7, titre: 'Mon titre'}))};
|
||||
throw new Error(`unexpected uid: ${uid}`);
|
||||
})
|
||||
},
|
||||
plugins: {email: {services: {email: {send: emailSend}}}}
|
||||
}
|
||||
};
|
||||
|
||||
const {afterCreate} = await loadLifecycles(strapiMock)
|
||||
const {afterCreate} = await loadLifecycles(strapiMock);
|
||||
|
||||
await afterCreate({params: {data: {user: 1, parole: 7, contenu: '<img src=x onerror=alert(1)>'}}})
|
||||
await afterCreate({params: {data: {user: 1, parole: 7, contenu: '<img src=x onerror=alert(1)>'}}});
|
||||
|
||||
expect(emailSend).toHaveBeenCalledTimes(1)
|
||||
const [payload] = emailSend.mock.calls[0]
|
||||
expect(payload.text).toBe('<img src=x onerror=alert(1)>')
|
||||
expect(payload.html).toBeUndefined()
|
||||
})
|
||||
})
|
||||
expect(emailSend).toHaveBeenCalledTimes(1);
|
||||
const [payload] = emailSend.mock.calls[0];
|
||||
expect(payload.text).toBe('<img src=x onerror=alert(1)>');
|
||||
expect(payload.html).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,41 +1,41 @@
|
||||
import {describe, it, expect, vi} from 'vitest'
|
||||
import {describe, it, expect, vi} from 'vitest';
|
||||
|
||||
const {default: createController} = await import('../commentaire.js')
|
||||
const {default: createController} = await import('../commentaire.js');
|
||||
|
||||
const dbUser = {id: 1, username: 'foo', email: 'foo@bar.com'}
|
||||
const dbParole = {id: 7, documentId: 'parole-doc-7'}
|
||||
const dbUser = {id: 1, username: 'foo', email: 'foo@bar.com'};
|
||||
const dbParole = {id: 7, documentId: 'parole-doc-7'};
|
||||
|
||||
function buildStrapi({existingParole = dbParole} = {}) {
|
||||
const commentaireDocuments = {
|
||||
create: vi.fn(async ({data}) => ({id: 99, ...data}))
|
||||
}
|
||||
};
|
||||
const paroleDocuments = {
|
||||
update: vi.fn(async () => {})
|
||||
}
|
||||
};
|
||||
const userDbQuery = {
|
||||
findOne: vi.fn(async ({where}) => (where.id === dbUser.id ? dbUser : null))
|
||||
}
|
||||
};
|
||||
const paroleDbQuery = {
|
||||
findOne: vi.fn(async ({where}) => (where.id === existingParole?.id ? existingParole : null))
|
||||
}
|
||||
};
|
||||
|
||||
const strapi = {
|
||||
contentType: vi.fn(() => ({uid: 'api::commentaire.commentaire', kind: 'collectionType'})),
|
||||
db: {
|
||||
query: vi.fn(uid => {
|
||||
if (uid === 'plugin::users-permissions.user') return userDbQuery
|
||||
if (uid === 'api::parole.parole') return paroleDbQuery
|
||||
throw new Error(`unexpected uid: ${uid}`)
|
||||
if (uid === 'plugin::users-permissions.user') return userDbQuery;
|
||||
if (uid === 'api::parole.parole') return paroleDbQuery;
|
||||
throw new Error(`unexpected uid: ${uid}`);
|
||||
})
|
||||
},
|
||||
documents: vi.fn(uid => {
|
||||
if (uid === 'api::commentaire.commentaire') return commentaireDocuments
|
||||
if (uid === 'api::parole.parole') return paroleDocuments
|
||||
throw new Error(`unexpected uid: ${uid}`)
|
||||
if (uid === 'api::commentaire.commentaire') return commentaireDocuments;
|
||||
if (uid === 'api::parole.parole') return paroleDocuments;
|
||||
throw new Error(`unexpected uid: ${uid}`);
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
return {strapi, commentaireDocuments, paroleDocuments, userDbQuery, paroleDbQuery}
|
||||
return {strapi, commentaireDocuments, paroleDocuments, userDbQuery, paroleDbQuery};
|
||||
}
|
||||
|
||||
function buildCtx(data) {
|
||||
@@ -44,7 +44,7 @@ function buildCtx(data) {
|
||||
body: {data},
|
||||
header: {authorization: 'Bearer faketoken'}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function buildData(overrides = {}) {
|
||||
@@ -54,58 +54,58 @@ function buildData(overrides = {}) {
|
||||
parole: dbParole.id,
|
||||
user: {...dbUser},
|
||||
...overrides
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('commentaire.create', () => {
|
||||
it('retrouve la parole par son id (pas par le documentId du user) et l\'associe correctement', async () => {
|
||||
const {strapi, commentaireDocuments, paroleDocuments, paroleDbQuery} = buildStrapi()
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData())
|
||||
const {strapi, commentaireDocuments, paroleDocuments, paroleDbQuery} = buildStrapi();
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData());
|
||||
|
||||
await controller.create(ctx)
|
||||
await controller.create(ctx);
|
||||
|
||||
expect(paroleDbQuery.findOne).toHaveBeenCalledWith({where: {id: dbParole.id}})
|
||||
expect(commentaireDocuments.create).toHaveBeenCalled()
|
||||
expect(paroleDbQuery.findOne).toHaveBeenCalledWith({where: {id: dbParole.id}});
|
||||
expect(commentaireDocuments.create).toHaveBeenCalled();
|
||||
expect(paroleDocuments.update).toHaveBeenCalledWith({
|
||||
documentId: dbParole.documentId,
|
||||
data: {commentaires: {connect: [99]}}
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
it('rejette quand la parole ciblée n\'existe pas', async () => {
|
||||
const {strapi, commentaireDocuments} = buildStrapi({existingParole: null})
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData())
|
||||
const {strapi, commentaireDocuments} = buildStrapi({existingParole: null});
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData());
|
||||
|
||||
await expect(controller.create(ctx)).rejects.toThrow('Texte introuvable.')
|
||||
expect(commentaireDocuments.create).not.toHaveBeenCalled()
|
||||
})
|
||||
await expect(controller.create(ctx)).rejects.toThrow('Texte introuvable.');
|
||||
expect(commentaireDocuments.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuse sans planter quand data.user est absent', async () => {
|
||||
const {strapi, userDbQuery} = buildStrapi()
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData({user: undefined}))
|
||||
const {strapi, userDbQuery} = buildStrapi();
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData({user: undefined}));
|
||||
|
||||
await expect(controller.create(ctx)).rejects.toThrow('Informations manquantes.')
|
||||
expect(userDbQuery.findOne).not.toHaveBeenCalled()
|
||||
})
|
||||
await expect(controller.create(ctx)).rejects.toThrow('Informations manquantes.');
|
||||
expect(userDbQuery.findOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuse sans planter quand data.parole est absent', async () => {
|
||||
const {strapi, paroleDbQuery} = buildStrapi()
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData({parole: undefined}))
|
||||
const {strapi, paroleDbQuery} = buildStrapi();
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData({parole: undefined}));
|
||||
|
||||
await expect(controller.create(ctx)).rejects.toThrow('Informations manquantes.')
|
||||
expect(paroleDbQuery.findOne).not.toHaveBeenCalled()
|
||||
})
|
||||
await expect(controller.create(ctx)).rejects.toThrow('Informations manquantes.');
|
||||
expect(paroleDbQuery.findOne).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignore les champs non autorisés du payload (mass assignment)', async () => {
|
||||
const {strapi, commentaireDocuments} = buildStrapi()
|
||||
const controller = createController({strapi})
|
||||
const ctx = buildCtx(buildData({publishedAt: '2020-01-01'}))
|
||||
const {strapi, commentaireDocuments} = buildStrapi();
|
||||
const controller = createController({strapi});
|
||||
const ctx = buildCtx(buildData({publishedAt: '2020-01-01'}));
|
||||
|
||||
await controller.create(ctx)
|
||||
await controller.create(ctx);
|
||||
|
||||
expect(commentaireDocuments.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
@@ -114,6 +114,6 @@ describe('commentaire.create', () => {
|
||||
user: dbUser.id,
|
||||
parole: dbParole.id
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
const { createCoreController } = require('@strapi/strapi').factories;
|
||||
const { ApplicationError, NotFoundError } = require("@strapi/utils").errors
|
||||
const { ApplicationError, NotFoundError } = require('@strapi/utils').errors;
|
||||
|
||||
module.exports = createCoreController('api::commentaire.commentaire', ({strapi}) => ({
|
||||
async create(ctx) {
|
||||
const {body} = ctx.request
|
||||
let {data} = body
|
||||
const {body} = ctx.request;
|
||||
let {data} = body;
|
||||
|
||||
if (!data?.user?.id || !data?.parole) {
|
||||
throw new ApplicationError('Informations manquantes.')
|
||||
throw new ApplicationError('Informations manquantes.');
|
||||
}
|
||||
|
||||
const user = await strapi.db.query('plugin::users-permissions.user').findOne({
|
||||
where: {id: data.user.id}
|
||||
})
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new NotFoundError('Utilisateur introuvable.')
|
||||
throw new NotFoundError('Utilisateur introuvable.');
|
||||
}
|
||||
|
||||
if (user.id !== data.user.id || user.username !== data.user.username || user.email !== data.user.email) {
|
||||
throw new ApplicationError('Informations non valides.')
|
||||
throw new ApplicationError('Informations non valides.');
|
||||
}
|
||||
|
||||
const parole = await strapi.db.query('api::parole.parole').findOne({
|
||||
where: {id: data.parole}
|
||||
})
|
||||
});
|
||||
|
||||
if (!parole) {
|
||||
throw new NotFoundError('Texte introuvable.')
|
||||
throw new NotFoundError('Texte introuvable.');
|
||||
}
|
||||
|
||||
const newCommentaire = await strapi.documents('api::commentaire.commentaire').create({
|
||||
@@ -39,7 +39,7 @@ module.exports = createCoreController('api::commentaire.commentaire', ({strapi})
|
||||
user: user.id,
|
||||
parole: parole.id
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
await strapi.documents('api::parole.parole').update({
|
||||
documentId: parole.documentId,
|
||||
@@ -47,8 +47,8 @@ module.exports = createCoreController('api::commentaire.commentaire', ({strapi})
|
||||
data: {
|
||||
commentaires: {connect: [newCommentaire.id]}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
return newCommentaire;
|
||||
}
|
||||
}))
|
||||
}));
|
||||
|
||||
@@ -14,4 +14,4 @@ module.exports = createCoreRouter('api::commentaire.commentaire', {
|
||||
policies: [{name: 'global::is-document-owner', config: {uid: 'api::commentaire.commentaire'}}]
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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';
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,4 +9,4 @@ module.exports = {
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
@@ -1,11 +1,11 @@
|
||||
import {describe, it, expect, vi} from 'vitest'
|
||||
import {describe, it, expect, vi} from 'vitest';
|
||||
|
||||
const {default: isDocumentOwner} = await import('../is-document-owner.js')
|
||||
const {default: isDocumentOwner} = await import('../is-document-owner.js');
|
||||
|
||||
function buildStrapi({jwtUserId, document}) {
|
||||
const dbQuery = {
|
||||
findOne: vi.fn(async () => document)
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
plugins: {
|
||||
@@ -21,7 +21,7 @@ function buildStrapi({jwtUserId, document}) {
|
||||
query: vi.fn(() => dbQuery)
|
||||
},
|
||||
dbQuery
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function buildPolicyContext({authorization = 'Bearer faketoken', paramId, bodyDocumentId} = {}) {
|
||||
@@ -31,43 +31,43 @@ function buildPolicyContext({authorization = 'Bearer faketoken', paramId, bodyDo
|
||||
header: authorization ? {authorization} : {},
|
||||
body: {data: {documentId: bodyDocumentId}}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('is-document-owner policy', () => {
|
||||
it("refuse quand aucun en-tête d'autorisation n'est présent", async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: {documentId: 'doc-1', user: {id: 1}}})
|
||||
const policyContext = buildPolicyContext({authorization: null, paramId: 'doc-1'})
|
||||
it('refuse quand aucun en-tête d\'autorisation n\'est présent', async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: {documentId: 'doc-1', user: {id: 1}}});
|
||||
const policyContext = buildPolicyContext({authorization: null, paramId: 'doc-1'});
|
||||
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).rejects.toThrow('Opération non autorisée')
|
||||
})
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).rejects.toThrow('Opération non autorisée');
|
||||
});
|
||||
|
||||
it('autorise quand le user du JWT est le propriétaire du document (id dans les params)', async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: {documentId: 'doc-1', user: {id: 1}}})
|
||||
const policyContext = buildPolicyContext({paramId: 'doc-1'})
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: {documentId: 'doc-1', user: {id: 1}}});
|
||||
const policyContext = buildPolicyContext({paramId: 'doc-1'});
|
||||
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).resolves.toBe(true)
|
||||
expect(strapi.dbQuery.findOne).toHaveBeenCalledWith({where: {documentId: 'doc-1'}, populate: {user: true}})
|
||||
})
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).resolves.toBe(true);
|
||||
expect(strapi.dbQuery.findOne).toHaveBeenCalledWith({where: {documentId: 'doc-1'}, populate: {user: true}});
|
||||
});
|
||||
|
||||
it('autorise quand le documentId vient du corps de la requête (cas du contrôleur parole.update)', async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: {documentId: 'doc-1', user: {id: 1}}})
|
||||
const policyContext = buildPolicyContext({bodyDocumentId: 'doc-1'})
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: {documentId: 'doc-1', user: {id: 1}}});
|
||||
const policyContext = buildPolicyContext({bodyDocumentId: 'doc-1'});
|
||||
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).resolves.toBe(true)
|
||||
})
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("refuse quand le user du JWT n'est pas le propriétaire du document", async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 999, document: {documentId: 'doc-1', user: {id: 1}}})
|
||||
const policyContext = buildPolicyContext({paramId: 'doc-1'})
|
||||
it('refuse quand le user du JWT n\'est pas le propriétaire du document', async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 999, document: {documentId: 'doc-1', user: {id: 1}}});
|
||||
const policyContext = buildPolicyContext({paramId: 'doc-1'});
|
||||
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).rejects.toThrow('Opération non autorisée')
|
||||
})
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).rejects.toThrow('Opération non autorisée');
|
||||
});
|
||||
|
||||
it("refuse quand le document ciblé n'existe pas", async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: null})
|
||||
const policyContext = buildPolicyContext({paramId: 'doc-inconnu'})
|
||||
it('refuse quand le document ciblé n\'existe pas', async () => {
|
||||
const strapi = buildStrapi({jwtUserId: 1, document: null});
|
||||
const policyContext = buildPolicyContext({paramId: 'doc-inconnu'});
|
||||
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).rejects.toThrow('Ressource introuvable.')
|
||||
})
|
||||
})
|
||||
await expect(isDocumentOwner(policyContext, {uid: 'api::parole.parole'}, {strapi})).rejects.toThrow('Ressource introuvable.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {describe, it, expect, vi} from 'vitest'
|
||||
import {describe, it, expect, vi} from 'vitest';
|
||||
|
||||
const {default: isPayloadOwner} = await import('../is-payload-owner.js')
|
||||
const {default: isPayloadOwner} = await import('../is-payload-owner.js');
|
||||
|
||||
function buildStrapi(jwtUserId) {
|
||||
return {
|
||||
@@ -13,7 +13,7 @@ function buildStrapi(jwtUserId) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function buildPolicyContext({authorization, payloadUserId}) {
|
||||
@@ -22,30 +22,30 @@ function buildPolicyContext({authorization, payloadUserId}) {
|
||||
header: authorization ? {authorization} : {},
|
||||
body: {data: {user: {id: payloadUserId}}}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe('is-payload-owner policy', () => {
|
||||
it("refuse quand aucun en-tête d'autorisation n'est présent", async () => {
|
||||
const strapi = buildStrapi(999)
|
||||
const policyContext = buildPolicyContext({authorization: undefined, payloadUserId: 1})
|
||||
it('refuse quand aucun en-tête d\'autorisation n\'est présent', async () => {
|
||||
const strapi = buildStrapi(999);
|
||||
const policyContext = buildPolicyContext({authorization: undefined, payloadUserId: 1});
|
||||
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).rejects.toThrow('Opération non autorisée')
|
||||
})
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).rejects.toThrow('Opération non autorisée');
|
||||
});
|
||||
|
||||
it('autorise quand le user du JWT correspond au user du payload', async () => {
|
||||
const strapi = buildStrapi(1)
|
||||
const policyContext = buildPolicyContext({authorization: 'Bearer faketoken', payloadUserId: 1})
|
||||
const strapi = buildStrapi(1);
|
||||
const policyContext = buildPolicyContext({authorization: 'Bearer faketoken', payloadUserId: 1});
|
||||
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).resolves.toBe(true)
|
||||
})
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('refuse quand le user du JWT ne correspond pas au user du payload', async () => {
|
||||
const strapi = buildStrapi(999)
|
||||
const policyContext = buildPolicyContext({authorization: 'Bearer faketoken', payloadUserId: 1})
|
||||
const strapi = buildStrapi(999);
|
||||
const policyContext = buildPolicyContext({authorization: 'Bearer faketoken', payloadUserId: 1});
|
||||
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).rejects.toThrow('Opération non autorisée')
|
||||
})
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).rejects.toThrow('Opération non autorisée');
|
||||
});
|
||||
|
||||
it('refuse quand le token est invalide', async () => {
|
||||
const strapi = {
|
||||
@@ -54,15 +54,15 @@ describe('is-payload-owner policy', () => {
|
||||
services: {
|
||||
jwt: {
|
||||
getToken: vi.fn(async () => {
|
||||
throw new Error('Invalid token.')
|
||||
throw new Error('Invalid token.');
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const policyContext = buildPolicyContext({authorization: 'Bearer faketoken', payloadUserId: 1})
|
||||
};
|
||||
const policyContext = buildPolicyContext({authorization: 'Bearer faketoken', payloadUserId: 1});
|
||||
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).rejects.toThrow('Opération non autorisée')
|
||||
})
|
||||
})
|
||||
await expect(isPayloadOwner(policyContext, {}, {strapi})).rejects.toThrow('Opération non autorisée');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
const { UnauthorizedError, NotFoundError } = require('@strapi/utils').errors
|
||||
const { UnauthorizedError, NotFoundError } = require('@strapi/utils').errors;
|
||||
|
||||
module.exports = async (policyContext, config, {strapi}) => {
|
||||
const {request, params} = policyContext
|
||||
const {request, params} = policyContext;
|
||||
|
||||
if (!request?.header?.authorization) {
|
||||
throw new UnauthorizedError('Opération non autorisée')
|
||||
throw new UnauthorizedError('Opération non autorisée');
|
||||
}
|
||||
|
||||
let jwtUserId
|
||||
let jwtUserId;
|
||||
try {
|
||||
({id: jwtUserId} = await strapi.plugins['users-permissions'].services.jwt.getToken(policyContext))
|
||||
({id: jwtUserId} = await strapi.plugins['users-permissions'].services.jwt.getToken(policyContext));
|
||||
} catch (err) {
|
||||
throw new UnauthorizedError('Opération non autorisée')
|
||||
throw new UnauthorizedError('Opération non autorisée');
|
||||
}
|
||||
|
||||
const documentId = params?.id ?? request.body?.data?.documentId
|
||||
const documentId = params?.id ?? request.body?.data?.documentId;
|
||||
|
||||
const document = await strapi.db.query(config.uid).findOne({
|
||||
where: {documentId},
|
||||
populate: {user: true}
|
||||
})
|
||||
});
|
||||
|
||||
if (!document) {
|
||||
throw new NotFoundError('Ressource introuvable.')
|
||||
throw new NotFoundError('Ressource introuvable.');
|
||||
}
|
||||
|
||||
if (document.user?.id !== jwtUserId) {
|
||||
throw new UnauthorizedError('Opération non autorisée')
|
||||
throw new UnauthorizedError('Opération non autorisée');
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
'use strict';
|
||||
|
||||
const { UnauthorizedError } = require('@strapi/utils').errors
|
||||
const { UnauthorizedError } = require('@strapi/utils').errors;
|
||||
|
||||
module.exports = async (policyContext, config, {strapi}) => {
|
||||
const {request} = policyContext
|
||||
const {request} = policyContext;
|
||||
|
||||
if (!request?.header?.authorization) {
|
||||
throw new UnauthorizedError('Opération non autorisée')
|
||||
throw new UnauthorizedError('Opération non autorisée');
|
||||
}
|
||||
|
||||
try {
|
||||
const {id} = await strapi.plugins['users-permissions'].services.jwt.getToken(policyContext)
|
||||
const {id} = await strapi.plugins['users-permissions'].services.jwt.getToken(policyContext);
|
||||
|
||||
if (id !== request.body?.data?.user?.id) {
|
||||
throw new UnauthorizedError('Opération non autorisée')
|
||||
throw new UnauthorizedError('Opération non autorisée');
|
||||
}
|
||||
} catch (err) {
|
||||
throw new UnauthorizedError('Opération non autorisée')
|
||||
throw new UnauthorizedError('Opération non autorisée');
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -1,62 +1,62 @@
|
||||
import {describe, it, expect, afterEach} from 'vitest'
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import {backupDatabase} from '../backup-database.js'
|
||||
import {describe, it, expect, afterEach} from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import {backupDatabase} from '../backup-database.js';
|
||||
|
||||
const tmpDirs = []
|
||||
const tmpDirs = [];
|
||||
|
||||
function makeTmpDir() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'backup-database-test-'))
|
||||
tmpDirs.push(dir)
|
||||
return dir
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'backup-database-test-'));
|
||||
tmpDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe('backupDatabase', () => {
|
||||
afterEach(() => {
|
||||
for (const dir of tmpDirs.splice(0)) {
|
||||
fs.rmSync(dir, {recursive: true, force: true})
|
||||
fs.rmSync(dir, {recursive: true, force: true});
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
it("ne fait rien quand le fichier de base n'existe pas", () => {
|
||||
const root = makeTmpDir()
|
||||
it('ne fait rien quand le fichier de base n\'existe pas', () => {
|
||||
const root = makeTmpDir();
|
||||
const result = backupDatabase({
|
||||
dbPath: path.join(root, 'inexistant.db'),
|
||||
backupsDir: path.join(root, 'backups')
|
||||
})
|
||||
});
|
||||
|
||||
expect(result).toBeNull()
|
||||
expect(fs.existsSync(path.join(root, 'backups'))).toBe(false)
|
||||
})
|
||||
expect(result).toBeNull();
|
||||
expect(fs.existsSync(path.join(root, 'backups'))).toBe(false);
|
||||
});
|
||||
|
||||
it('copie le fichier de base dans le dossier de sauvegardes', () => {
|
||||
const root = makeTmpDir()
|
||||
const dbPath = path.join(root, 'data.db')
|
||||
fs.writeFileSync(dbPath, 'contenu-de-la-base')
|
||||
const backupsDir = path.join(root, 'backups')
|
||||
const root = makeTmpDir();
|
||||
const dbPath = path.join(root, 'data.db');
|
||||
fs.writeFileSync(dbPath, 'contenu-de-la-base');
|
||||
const backupsDir = path.join(root, 'backups');
|
||||
|
||||
const result = backupDatabase({dbPath, backupsDir})
|
||||
const result = backupDatabase({dbPath, backupsDir});
|
||||
|
||||
expect(result).not.toBeNull()
|
||||
expect(fs.existsSync(result)).toBe(true)
|
||||
expect(fs.readFileSync(result, 'utf8')).toBe('contenu-de-la-base')
|
||||
})
|
||||
expect(result).not.toBeNull();
|
||||
expect(fs.existsSync(result)).toBe(true);
|
||||
expect(fs.readFileSync(result, 'utf8')).toBe('contenu-de-la-base');
|
||||
});
|
||||
|
||||
it('ne conserve que les 8 sauvegardes les plus récentes', () => {
|
||||
const root = makeTmpDir()
|
||||
const dbPath = path.join(root, 'data.db')
|
||||
fs.writeFileSync(dbPath, 'contenu')
|
||||
const backupsDir = path.join(root, 'backups')
|
||||
fs.mkdirSync(backupsDir, {recursive: true})
|
||||
const root = makeTmpDir();
|
||||
const dbPath = path.join(root, 'data.db');
|
||||
fs.writeFileSync(dbPath, 'contenu');
|
||||
const backupsDir = path.join(root, 'backups');
|
||||
fs.mkdirSync(backupsDir, {recursive: true});
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
fs.writeFileSync(path.join(backupsDir, `data-2020-01-0${i}.db`), 'ancien')
|
||||
fs.writeFileSync(path.join(backupsDir, `data-2020-01-0${i}.db`), 'ancien');
|
||||
}
|
||||
|
||||
backupDatabase({dbPath, backupsDir})
|
||||
backupDatabase({dbPath, backupsDir});
|
||||
|
||||
const remaining = fs.readdirSync(backupsDir).filter(name => name.startsWith('data-'))
|
||||
expect(remaining).toHaveLength(8)
|
||||
})
|
||||
})
|
||||
const remaining = fs.readdirSync(backupsDir).filter(name => name.startsWith('data-'));
|
||||
expect(remaining).toHaveLength(8);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user