|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const syncSlugCount = async (settings) => { |
| 4 | + const entries = await strapi.entityService.findMany('plugin::slugify.slug', { |
| 5 | + filters: { createdAt: { $gt: 1 } }, |
| 6 | + }); |
| 7 | + |
| 8 | + // if entries aready present we can skip sync |
| 9 | + if (entries && entries.length) { |
| 10 | + return; |
| 11 | + } |
| 12 | + |
| 13 | + strapi.log.info('[slugify] syncing slug count for registered content types'); |
| 14 | + |
| 15 | + const slugs = new Map(); |
| 16 | + |
| 17 | + // chec slugs in each reigistered model |
| 18 | + for (const uid in settings.modelsByUID) { |
| 19 | + if (!Object.hasOwnProperty.call(settings.modelsByUID, uid)) { |
| 20 | + continue; |
| 21 | + } |
| 22 | + |
| 23 | + const model = settings.modelsByUID[uid]; |
| 24 | + |
| 25 | + // using db query to avoid the need to check if CT has draftAndPublish enabled |
| 26 | + const modelEntries = await strapi.db.query(model.uid).findMany({ |
| 27 | + filters: { createdAt: { $gt: 1 } }, |
| 28 | + }); |
| 29 | + |
| 30 | + strapi.log.info(`[slugify] syncing slug count for ${model.uid}`); |
| 31 | + for (const entry of modelEntries) { |
| 32 | + const slug = entry[model.field]; |
| 33 | + if (!slug) { |
| 34 | + continue; |
| 35 | + } |
| 36 | + |
| 37 | + const record = slugs.get(getNonAppendedSlug(slug)); |
| 38 | + if (!record) { |
| 39 | + slugs.set(slug, { slug, count: 1 }); |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + slugs.set(record.slug, { slug: record.slug, count: record.count + 1 }); |
| 44 | + } |
| 45 | + strapi.log.info(`[slugify] sync for ${model.uid} completed`); |
| 46 | + } |
| 47 | + |
| 48 | + if (slugs.size) { |
| 49 | + // create all required records |
| 50 | + const createResponse = await strapi.db.query('plugin::slugify.slug').createMany({ |
| 51 | + data: [...slugs.values()], |
| 52 | + }); |
| 53 | + |
| 54 | + strapi.log.info( |
| 55 | + `[slugify] ${createResponse.count} out of ${slugs.size} slugs synced successfully` |
| 56 | + ); |
| 57 | + } else { |
| 58 | + strapi.log.info('[slugify] No syncable slugs found'); |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +// removes any appended number from a slug/string if found |
| 63 | +const getNonAppendedSlug = (slug) => { |
| 64 | + const match = slug.match('[\\-]{1}[\\d]+$'); |
| 65 | + |
| 66 | + if (!match) { |
| 67 | + return slug; |
| 68 | + } |
| 69 | + |
| 70 | + return slug.replace(match[0], ''); |
| 71 | +}; |
| 72 | + |
| 73 | +module.exports = { |
| 74 | + syncSlugCount, |
| 75 | +}; |
0 commit comments