@strapi/content-manager 0.0.0-next.e50ef5e2ea57ecf3da5bcf308508b51ee3c0deca → 0.0.0-next.e5d4b412da0d932b61b2fa5012d16513fda6de04
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/components/Widgets.js +267 -9
- package/dist/admin/components/Widgets.js.map +1 -1
- package/dist/admin/components/Widgets.mjs +250 -12
- package/dist/admin/components/Widgets.mjs.map +1 -1
- package/dist/admin/hooks/useDocumentActions.js +0 -3
- package/dist/admin/hooks/useDocumentActions.js.map +1 -1
- package/dist/admin/hooks/useDocumentActions.mjs +1 -4
- package/dist/admin/hooks/useDocumentActions.mjs.map +1 -1
- package/dist/admin/index.js +45 -8
- package/dist/admin/index.js.map +1 -1
- package/dist/admin/index.mjs +46 -9
- package/dist/admin/index.mjs.map +1 -1
- package/dist/admin/layout.js +1 -27
- package/dist/admin/layout.js.map +1 -1
- package/dist/admin/layout.mjs +2 -9
- package/dist/admin/layout.mjs.map +1 -1
- package/dist/admin/pages/EditView/EditViewPage.js +11 -5
- package/dist/admin/pages/EditView/EditViewPage.js.map +1 -1
- package/dist/admin/pages/EditView/EditViewPage.mjs +13 -7
- package/dist/admin/pages/EditView/EditViewPage.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/DocumentActions.js +18 -3
- package/dist/admin/pages/EditView/components/DocumentActions.js.map +1 -1
- package/dist/admin/pages/EditView/components/DocumentActions.mjs +19 -4
- package/dist/admin/pages/EditView/components/DocumentActions.mjs.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.js +4 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.js.map +1 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.mjs +4 -1
- package/dist/admin/pages/EditView/components/FormInputs/Relations/Relations.mjs.map +1 -1
- package/dist/admin/pages/EditView/utils/data.js +7 -1
- package/dist/admin/pages/EditView/utils/data.js.map +1 -1
- package/dist/admin/pages/EditView/utils/data.mjs +7 -1
- package/dist/admin/pages/EditView/utils/data.mjs.map +1 -1
- package/dist/admin/pages/ListView/ListViewPage.js +152 -143
- package/dist/admin/pages/ListView/ListViewPage.js.map +1 -1
- package/dist/admin/pages/ListView/ListViewPage.mjs +153 -144
- package/dist/admin/pages/ListView/ListViewPage.mjs.map +1 -1
- package/dist/admin/pages/ListView/components/BulkActions/PublishAction.js +12 -2
- package/dist/admin/pages/ListView/components/BulkActions/PublishAction.js.map +1 -1
- package/dist/admin/pages/ListView/components/BulkActions/PublishAction.mjs +12 -2
- package/dist/admin/pages/ListView/components/BulkActions/PublishAction.mjs.map +1 -1
- package/dist/admin/pages/ListView/components/Filters.js +3 -1
- package/dist/admin/pages/ListView/components/Filters.js.map +1 -1
- package/dist/admin/pages/ListView/components/Filters.mjs +3 -1
- package/dist/admin/pages/ListView/components/Filters.mjs.map +1 -1
- package/dist/admin/preview/components/PreviewSidePanel.js +31 -4
- package/dist/admin/preview/components/PreviewSidePanel.js.map +1 -1
- package/dist/admin/preview/components/PreviewSidePanel.mjs +32 -5
- package/dist/admin/preview/components/PreviewSidePanel.mjs.map +1 -1
- package/dist/admin/preview/pages/Preview.js +136 -35
- package/dist/admin/preview/pages/Preview.js.map +1 -1
- package/dist/admin/preview/pages/Preview.mjs +137 -36
- package/dist/admin/preview/pages/Preview.mjs.map +1 -1
- package/dist/admin/preview/utils/constants.js +21 -0
- package/dist/admin/preview/utils/constants.js.map +1 -0
- package/dist/admin/preview/utils/constants.mjs +19 -0
- package/dist/admin/preview/utils/constants.mjs.map +1 -0
- package/dist/admin/preview/utils/previewScript.js +203 -0
- package/dist/admin/preview/utils/previewScript.js.map +1 -0
- package/dist/admin/preview/utils/previewScript.mjs +201 -0
- package/dist/admin/preview/utils/previewScript.mjs.map +1 -0
- package/dist/admin/services/api.js +3 -1
- package/dist/admin/services/api.js.map +1 -1
- package/dist/admin/services/api.mjs +3 -1
- package/dist/admin/services/api.mjs.map +1 -1
- package/dist/admin/services/documents.js +40 -14
- package/dist/admin/services/documents.js.map +1 -1
- package/dist/admin/services/documents.mjs +40 -14
- package/dist/admin/services/documents.mjs.map +1 -1
- package/dist/admin/src/components/Widgets.d.ts +2 -1
- package/dist/admin/src/history/services/historyVersion.d.ts +1 -1
- package/dist/admin/src/preview/services/preview.d.ts +1 -1
- package/dist/admin/src/preview/utils/constants.d.ts +17 -0
- package/dist/admin/src/preview/utils/previewScript.d.ts +18 -0
- package/dist/admin/src/services/api.d.ts +1 -1
- package/dist/admin/src/services/components.d.ts +2 -2
- package/dist/admin/src/services/contentTypes.d.ts +3 -3
- package/dist/admin/src/services/documents.d.ts +16 -16
- package/dist/admin/src/services/homepage.d.ts +1 -1
- package/dist/admin/src/services/init.d.ts +1 -1
- package/dist/admin/src/services/relations.d.ts +2 -2
- package/dist/admin/src/services/uid.d.ts +3 -3
- package/dist/admin/src/utils/api.d.ts +1 -1
- package/dist/admin/translations/en.json.js +6 -0
- package/dist/admin/translations/en.json.js.map +1 -1
- package/dist/admin/translations/en.json.mjs +6 -0
- package/dist/admin/translations/en.json.mjs.map +1 -1
- package/dist/admin/translations/es.json.js +5 -2
- package/dist/admin/translations/es.json.js.map +1 -1
- package/dist/admin/translations/es.json.mjs +5 -2
- package/dist/admin/translations/es.json.mjs.map +1 -1
- package/dist/admin/translations/fr.json.js +4 -1
- package/dist/admin/translations/fr.json.js.map +1 -1
- package/dist/admin/translations/fr.json.mjs +4 -1
- package/dist/admin/translations/fr.json.mjs.map +1 -1
- package/dist/admin/utils/api.js +1 -1
- package/dist/admin/utils/api.js.map +1 -1
- package/dist/admin/utils/api.mjs +1 -1
- package/dist/admin/utils/api.mjs.map +1 -1
- package/dist/admin/utils/validation.js +2 -1
- package/dist/admin/utils/validation.js.map +1 -1
- package/dist/admin/utils/validation.mjs +2 -1
- package/dist/admin/utils/validation.mjs.map +1 -1
- package/dist/server/history/services/lifecycles.js +20 -19
- package/dist/server/history/services/lifecycles.js.map +1 -1
- package/dist/server/history/services/lifecycles.mjs +20 -19
- package/dist/server/history/services/lifecycles.mjs.map +1 -1
- package/dist/server/homepage/controllers/homepage.js +5 -0
- package/dist/server/homepage/controllers/homepage.js.map +1 -1
- package/dist/server/homepage/controllers/homepage.mjs +5 -0
- package/dist/server/homepage/controllers/homepage.mjs.map +1 -1
- package/dist/server/homepage/routes/homepage.js +11 -0
- package/dist/server/homepage/routes/homepage.js.map +1 -1
- package/dist/server/homepage/routes/homepage.mjs +11 -0
- package/dist/server/homepage/routes/homepage.mjs.map +1 -1
- package/dist/server/homepage/services/homepage.js +31 -0
- package/dist/server/homepage/services/homepage.js.map +1 -1
- package/dist/server/homepage/services/homepage.mjs +31 -0
- package/dist/server/homepage/services/homepage.mjs.map +1 -1
- package/dist/server/preview/services/preview-config.js +5 -1
- package/dist/server/preview/services/preview-config.js.map +1 -1
- package/dist/server/preview/services/preview-config.mjs +5 -1
- package/dist/server/preview/services/preview-config.mjs.map +1 -1
- package/dist/server/preview/services/preview.js +4 -0
- package/dist/server/preview/services/preview.js.map +1 -1
- package/dist/server/preview/services/preview.mjs +4 -0
- package/dist/server/preview/services/preview.mjs.map +1 -1
- package/dist/server/src/history/services/lifecycles.d.ts.map +1 -1
- package/dist/server/src/homepage/controllers/homepage.d.ts +2 -1
- package/dist/server/src/homepage/controllers/homepage.d.ts.map +1 -1
- package/dist/server/src/homepage/index.d.ts +5 -0
- package/dist/server/src/homepage/index.d.ts.map +1 -1
- package/dist/server/src/homepage/routes/homepage.d.ts.map +1 -1
- package/dist/server/src/homepage/services/homepage.d.ts +2 -1
- package/dist/server/src/homepage/services/homepage.d.ts.map +1 -1
- package/dist/server/src/homepage/services/index.d.ts +5 -0
- package/dist/server/src/homepage/services/index.d.ts.map +1 -1
- package/dist/server/src/index.d.ts +5 -0
- package/dist/server/src/index.d.ts.map +1 -1
- package/dist/server/src/preview/services/index.d.ts +1 -0
- package/dist/server/src/preview/services/index.d.ts.map +1 -1
- package/dist/server/src/preview/services/preview-config.d.ts +1 -0
- package/dist/server/src/preview/services/preview-config.d.ts.map +1 -1
- package/dist/server/src/preview/services/preview.d.ts.map +1 -1
- package/dist/server/src/preview/utils.d.ts +1 -0
- package/dist/server/src/preview/utils.d.ts.map +1 -1
- package/dist/server/src/services/index.d.ts +5 -0
- package/dist/server/src/services/index.d.ts.map +1 -1
- package/dist/shared/contracts/homepage.d.ts +13 -0
- package/dist/shared/contracts/homepage.d.ts.map +1 -1
- package/package.json +7 -8
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
var strapiUtils = require('@strapi/utils');
|
|
4
4
|
var fp = require('lodash/fp');
|
|
5
|
-
var nodeSchedule = require('node-schedule');
|
|
6
5
|
var utils$1 = require('../utils.js');
|
|
7
6
|
var constants = require('../constants.js');
|
|
8
7
|
var utils = require('./utils.js');
|
|
@@ -58,7 +57,6 @@ var utils = require('./utils.js');
|
|
|
58
57
|
};
|
|
59
58
|
const createLifecyclesService = ({ strapi: strapi1 })=>{
|
|
60
59
|
const state = {
|
|
61
|
-
deleteExpiredJob: null,
|
|
62
60
|
isInitialized: false
|
|
63
61
|
};
|
|
64
62
|
const serviceUtils = utils.createServiceUtils({
|
|
@@ -127,27 +125,30 @@ const createLifecyclesService = ({ strapi: strapi1 })=>{
|
|
|
127
125
|
return result;
|
|
128
126
|
});
|
|
129
127
|
// Schedule a job to delete expired history versions every day at midnight
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
128
|
+
strapi1.cron.add({
|
|
129
|
+
deleteHistoryDaily: {
|
|
130
|
+
async task () {
|
|
131
|
+
const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;
|
|
132
|
+
const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);
|
|
133
|
+
strapi1.db.query(constants.HISTORY_VERSION_UID).deleteMany({
|
|
134
|
+
where: {
|
|
135
|
+
created_at: {
|
|
136
|
+
$lt: expirationDate
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}).catch((error)=>{
|
|
140
|
+
if (error instanceof Error) {
|
|
141
|
+
strapi1.log.error('Error deleting expired history versions', error.message);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
options: '0 0 * * *'
|
|
146
|
+
}
|
|
144
147
|
});
|
|
145
148
|
state.isInitialized = true;
|
|
146
149
|
},
|
|
147
150
|
async destroy () {
|
|
148
|
-
|
|
149
|
-
state.deleteExpiredJob.cancel();
|
|
150
|
-
}
|
|
151
|
+
strapi1.cron.remove('deleteHistoryDaily');
|
|
151
152
|
}
|
|
152
153
|
};
|
|
153
154
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycles.js","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { scheduleJob } from 'node-schedule';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n deleteExpiredJob: ReturnType<typeof scheduleJob> | null;\n isInitialized: boolean;\n } = {\n deleteExpiredJob: null,\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n state.deleteExpiredJob = scheduleJob('historyDaily', '0 0 * * *', () => {\n const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n strapi.db\n .query(HISTORY_VERSION_UID)\n .deleteMany({\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n })\n .catch((error) => {\n if (error instanceof Error) {\n strapi.log.error('Error deleting expired history versions', error.message);\n }\n });\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n if (state.deleteExpiredJob) {\n state.deleteExpiredJob.cancel();\n }\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","deleteExpiredJob","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","scheduleJob","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","HISTORY_VERSION_UID","deleteMany","created_at","$lt","catch","error","Error","log","message","destroy","cancel"],"mappings":";;;;;;;;;AAaA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,WACnBP,OAAQO,CAAAA,MAAM,KAAK,SAAA,IACnBP,OAAQO,CAAAA,MAAM,KAAK,WACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,cACnB,EAAA;QACA,OAAO,KAAA;AACT;AAEA;;;;;AAKC,MACD,IACEP,OAAAA,CAAQO,MAAM,KAAK,QACnBN,IAAAA,MAAAA,CAAOC,cAAc,CAACC,GAAG,EAAA,EAAIC,OAAQC,CAAAA,GAAAA,CAAIG,SAAS,kBAClD,CAAA,EAAA;QACA,OAAO,KAAA;AACT;;IAGA,IAAI,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AAA,CAAAA;AAE7CxE,gBAAAA,OAAAA,CAAOoD,EAAE,CACNC,KAAK,CAACwB,6BAAAA,CAAAA,CACNC,UAAU,CAAC;oBACVvB,KAAO,EAAA;wBACLwB,UAAY,EAAA;4BACVC,GAAKN,EAAAA;AACP;AACF;iBAEDO,CAAAA,CAAAA,KAAK,CAAC,CAACC,KAAAA,GAAAA;AACN,oBAAA,IAAIA,iBAAiBC,KAAO,EAAA;AAC1BnF,wBAAAA,OAAAA,CAAOoF,GAAG,CAACF,KAAK,CAAC,yCAAA,EAA2CA,MAAMG,OAAO,CAAA;AAC3E;AACF,iBAAA,CAAA;AACJ,aAAA,CAAA;AAEAzD,YAAAA,KAAAA,CAAME,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAMwD,OAAAA,CAAAA,GAAAA;YACJ,IAAI1D,KAAAA,CAAMC,gBAAgB,EAAE;gBAC1BD,KAAMC,CAAAA,gBAAgB,CAAC0D,MAAM,EAAA;AAC/B;AACF;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"lifecycles.js","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n isInitialized: boolean;\n } = {\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n strapi.cron.add({\n deleteHistoryDaily: {\n async task() {\n const retentionDaysInMilliseconds =\n serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n strapi.db\n .query(HISTORY_VERSION_UID)\n .deleteMany({\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n })\n .catch((error) => {\n if (error instanceof Error) {\n strapi.log.error('Error deleting expired history versions', error.message);\n }\n });\n },\n options: '0 0 * * *',\n },\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n strapi.cron.remove('deleteHistoryDaily');\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","cron","add","deleteHistoryDaily","task","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","HISTORY_VERSION_UID","deleteMany","created_at","$lt","catch","error","Error","log","message","options","destroy","remove"],"mappings":";;;;;;;;AAWA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,WACnBP,OAAQO,CAAAA,MAAM,KAAK,SAAA,IACnBP,OAAQO,CAAAA,MAAM,KAAK,WACnBP,IAAAA,OAAAA,CAAQO,MAAM,KAAK,cACnB,EAAA;QACA,OAAO,KAAA;AACT;AAEA;;;;;AAKC,MACD,IACEP,OAAAA,CAAQO,MAAM,KAAK,QACnBN,IAAAA,MAAAA,CAAOC,cAAc,CAACC,GAAG,EAAA,EAAIC,OAAQC,CAAAA,GAAAA,CAAIG,SAAS,kBAClD,CAAA,EAAA;QACA,OAAO,KAAA;AACT;;IAGA,IA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;AAE7C1E,wBAAAA,OAAAA,CAAOmD,EAAE,CACNC,KAAK,CAAC2B,6BAAAA,CAAAA,CACNC,UAAU,CAAC;4BACV1B,KAAO,EAAA;gCACL2B,UAAY,EAAA;oCACVC,GAAKN,EAAAA;AACP;AACF;yBAEDO,CAAAA,CAAAA,KAAK,CAAC,CAACC,KAAAA,GAAAA;AACN,4BAAA,IAAIA,iBAAiBC,KAAO,EAAA;AAC1BrF,gCAAAA,OAAAA,CAAOsF,GAAG,CAACF,KAAK,CAAC,yCAAA,EAA2CA,MAAMG,OAAO,CAAA;AAC3E;AACF,yBAAA,CAAA;AACJ,qBAAA;oBACAC,OAAS,EAAA;AACX;AACF,aAAA,CAAA;AAEA5D,YAAAA,KAAAA,CAAMC,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAM4D,OAAAA,CAAAA,GAAAA;YACJzF,OAAOsE,CAAAA,IAAI,CAACoB,MAAM,CAAC,oBAAA,CAAA;AACrB;AACF,KAAA;AACF;;;;"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { contentTypes } from '@strapi/utils';
|
|
2
2
|
import { castArray, omit } from 'lodash/fp';
|
|
3
|
-
import { scheduleJob } from 'node-schedule';
|
|
4
3
|
import { getService } from '../utils.mjs';
|
|
5
4
|
import { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants.mjs';
|
|
6
5
|
import { createServiceUtils } from './utils.mjs';
|
|
@@ -56,7 +55,6 @@ import { createServiceUtils } from './utils.mjs';
|
|
|
56
55
|
};
|
|
57
56
|
const createLifecyclesService = ({ strapi: strapi1 })=>{
|
|
58
57
|
const state = {
|
|
59
|
-
deleteExpiredJob: null,
|
|
60
58
|
isInitialized: false
|
|
61
59
|
};
|
|
62
60
|
const serviceUtils = createServiceUtils({
|
|
@@ -125,27 +123,30 @@ const createLifecyclesService = ({ strapi: strapi1 })=>{
|
|
|
125
123
|
return result;
|
|
126
124
|
});
|
|
127
125
|
// Schedule a job to delete expired history versions every day at midnight
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
126
|
+
strapi1.cron.add({
|
|
127
|
+
deleteHistoryDaily: {
|
|
128
|
+
async task () {
|
|
129
|
+
const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;
|
|
130
|
+
const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);
|
|
131
|
+
strapi1.db.query(HISTORY_VERSION_UID).deleteMany({
|
|
132
|
+
where: {
|
|
133
|
+
created_at: {
|
|
134
|
+
$lt: expirationDate
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}).catch((error)=>{
|
|
138
|
+
if (error instanceof Error) {
|
|
139
|
+
strapi1.log.error('Error deleting expired history versions', error.message);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
},
|
|
143
|
+
options: '0 0 * * *'
|
|
144
|
+
}
|
|
142
145
|
});
|
|
143
146
|
state.isInitialized = true;
|
|
144
147
|
},
|
|
145
148
|
async destroy () {
|
|
146
|
-
|
|
147
|
-
state.deleteExpiredJob.cancel();
|
|
148
|
-
}
|
|
149
|
+
strapi1.cron.remove('deleteHistoryDaily');
|
|
149
150
|
}
|
|
150
151
|
};
|
|
151
152
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycles.mjs","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { scheduleJob } from 'node-schedule';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n deleteExpiredJob: ReturnType<typeof scheduleJob> | null;\n isInitialized: boolean;\n } = {\n deleteExpiredJob: null,\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n state.deleteExpiredJob = scheduleJob('historyDaily', '0 0 * * *', () => {\n const retentionDaysInMilliseconds = serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n strapi.db\n .query(HISTORY_VERSION_UID)\n .deleteMany({\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n })\n .catch((error) => {\n if (error instanceof Error) {\n strapi.log.error('Error deleting expired history versions', error.message);\n }\n });\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n if (state.deleteExpiredJob) {\n state.deleteExpiredJob.cancel();\n }\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","deleteExpiredJob","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","scheduleJob","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","HISTORY_VERSION_UID","deleteMany","created_at","$lt","catch","error","Error","log","message","destroy","cancel"],"mappings":";;;;;;;AAaA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,C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F;AACF,qBAAA,CAAA;AACF,iBAAA,CAAA;gBAEA,OAAOT,MAAAA;AACT,aAAA,CAAA;;AAGAX,YAAAA,KAAAA,CAAMC,gBAAgB,GAAG0C,WAAY,CAAA,cAAA,EAAgB,WAAa,EAAA,IAAA;AAChE,gBAAA,MAAMC,8BAA8BzC,YAAa0C,CAAAA,gBAAgB,EAAK,GAAA,EAAA,GAAK,KAAK,EAAK,GAAA,IAAA;AACrF,gBAAA,MAAMC,cAAiB,GAAA,IAAIC,IAAKA,CAAAA,IAAAA,CAAKC,GAAG,EAAKJ,GAAAA,2BAAAA,CAAAA;AAE7CxE,gBAAAA,OAAAA,CAAOoD,EAAE,CACNC,KAAK,CAACwB,mBAAAA,CAAAA,CACNC,UAAU,CAAC;oBACVvB,KAAO,EAAA;wBACLwB,UAAY,EAAA;4BACVC,GAAKN,EAAAA;AACP;AACF;iBAEDO,CAAAA,CAAAA,KAAK,CAAC,CAACC,KAAAA,GAAAA;AACN,oBAAA,IAAIA,iBAAiBC,KAAO,EAAA;AAC1BnF,wBAAAA,OAAAA,CAAOoF,GAAG,CAACF,KAAK,CAAC,yCAAA,EAA2CA,MAAMG,OAAO,CAAA;AAC3E;AACF,iBAAA,CAAA;AACJ,aAAA,CAAA;AAEAzD,YAAAA,KAAAA,CAAME,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAMwD,OAAAA,CAAAA,GAAAA;YACJ,IAAI1D,KAAAA,CAAMC,gBAAgB,EAAE;gBAC1BD,KAAMC,CAAAA,gBAAgB,CAAC0D,MAAM,EAAA;AAC/B;AACF;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"lifecycles.mjs","sources":["../../../../server/src/history/services/lifecycles.ts"],"sourcesContent":["import type { Core, Modules, UID } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport { omit, castArray } from 'lodash/fp';\n\nimport { getService } from '../utils';\nimport { FIELDS_TO_IGNORE, HISTORY_VERSION_UID } from '../constants';\n\nimport type { CreateHistoryVersion } from '../../../../shared/contracts/history-versions';\nimport { createServiceUtils } from './utils';\n\n/**\n * Filters out actions that should not create a history version.\n */\nconst shouldCreateHistoryVersion = (\n context: Modules.Documents.Middleware.Context\n): context is Modules.Documents.Middleware.Context & {\n action: 'create' | 'update' | 'clone' | 'publish' | 'unpublish' | 'discardDraft';\n contentType: UID.CollectionType;\n} => {\n // Ignore requests that are not related to the content manager\n if (!strapi.requestContext.get()?.request.url.startsWith('/content-manager')) {\n return false;\n }\n\n // NOTE: cannot do type narrowing with array includes\n if (\n context.action !== 'create' &&\n context.action !== 'update' &&\n context.action !== 'clone' &&\n context.action !== 'publish' &&\n context.action !== 'unpublish' &&\n context.action !== 'discardDraft'\n ) {\n return false;\n }\n\n /**\n * When a document is published, the draft version of the document is also updated.\n * It creates confusion for users because they see two history versions each publish action.\n * To avoid this, we silence the update action during a publish request,\n * so that they only see the published version of the document in the history.\n */\n if (\n context.action === 'update' &&\n strapi.requestContext.get()?.request.url.endsWith('/actions/publish')\n ) {\n return false;\n }\n\n // Ignore content types not created by the user\n if (!context.contentType.uid.startsWith('api::')) {\n return false;\n }\n\n return true;\n};\n\n/**\n * Returns the content type schema (and its components schemas).\n * Used to determine if changes were made in the content type builder since a history version was created.\n * And therefore which fields can be restored and which cannot.\n */\nconst getSchemas = (uid: UID.CollectionType) => {\n const attributesSchema = strapi.getModel(uid).attributes;\n\n // TODO: Handle nested components\n const componentsSchemas = Object.keys(attributesSchema).reduce(\n (currentComponentSchemas, key) => {\n const fieldSchema = attributesSchema[key];\n\n if (fieldSchema.type === 'component') {\n const componentSchema = strapi.getModel(fieldSchema.component).attributes;\n return {\n ...currentComponentSchemas,\n [fieldSchema.component]: componentSchema,\n };\n }\n\n // Ignore anything that's not a component\n return currentComponentSchemas;\n },\n {} as CreateHistoryVersion['componentsSchemas']\n );\n\n return {\n schema: omit(FIELDS_TO_IGNORE, attributesSchema) as CreateHistoryVersion['schema'],\n componentsSchemas,\n };\n};\n\nconst createLifecyclesService = ({ strapi }: { strapi: Core.Strapi }) => {\n const state: {\n isInitialized: boolean;\n } = {\n isInitialized: false,\n };\n\n const serviceUtils = createServiceUtils({ strapi });\n const { persistTablesWithPrefix } = strapi.service('admin::persist-tables');\n\n return {\n async bootstrap() {\n // Prevent initializing the service twice\n if (state.isInitialized) {\n return;\n }\n\n // Avoid data loss in case users temporarily don't have a license\n await persistTablesWithPrefix('strapi_history_versions');\n\n strapi.documents.use(async (context, next) => {\n const result = (await next()) as any;\n\n if (!shouldCreateHistoryVersion(context)) {\n return result;\n }\n\n // On create/clone actions, the documentId is not available before creating the action is executed\n const documentId =\n context.action === 'create' || context.action === 'clone'\n ? result.documentId\n : context.params.documentId;\n\n // Apply default locale if not available in the request\n const defaultLocale = await serviceUtils.getDefaultLocale();\n const locales = castArray(context.params?.locale || defaultLocale);\n if (!locales.length) {\n return result;\n }\n\n // All schemas related to the content type\n const uid = context.contentType.uid;\n const schemas = getSchemas(uid);\n const model = strapi.getModel(uid);\n\n const isLocalizedContentType = serviceUtils.isLocalizedContentType(model);\n\n // Find all affected entries\n const localeEntries = await strapi.db.query(uid).findMany({\n where: {\n documentId,\n ...(isLocalizedContentType ? { locale: { $in: locales } } : {}),\n ...(contentTypes.hasDraftAndPublish(strapi.contentTypes[uid])\n ? { publishedAt: null }\n : {}),\n },\n populate: serviceUtils.getDeepPopulate(uid, true /* use database syntax */),\n });\n\n await strapi.db.transaction(async ({ onCommit }) => {\n // .createVersion() is executed asynchronously,\n // onCommit prevents creating a history version\n // when the transaction has already been committed\n onCommit(async () => {\n for (const entry of localeEntries) {\n const status = await serviceUtils.getVersionStatus(uid, entry);\n\n await getService(strapi, 'history').createVersion({\n contentType: uid,\n data: omit(FIELDS_TO_IGNORE, entry) as Modules.Documents.AnyDocument,\n relatedDocumentId: documentId,\n locale: entry.locale,\n status,\n ...schemas,\n });\n }\n });\n });\n\n return result;\n });\n\n // Schedule a job to delete expired history versions every day at midnight\n strapi.cron.add({\n deleteHistoryDaily: {\n async task() {\n const retentionDaysInMilliseconds =\n serviceUtils.getRetentionDays() * 24 * 60 * 60 * 1000;\n const expirationDate = new Date(Date.now() - retentionDaysInMilliseconds);\n\n strapi.db\n .query(HISTORY_VERSION_UID)\n .deleteMany({\n where: {\n created_at: {\n $lt: expirationDate,\n },\n },\n })\n .catch((error) => {\n if (error instanceof Error) {\n strapi.log.error('Error deleting expired history versions', error.message);\n }\n });\n },\n options: '0 0 * * *',\n },\n });\n\n state.isInitialized = true;\n },\n\n async destroy() {\n strapi.cron.remove('deleteHistoryDaily');\n },\n };\n};\n\nexport { createLifecyclesService };\n"],"names":["shouldCreateHistoryVersion","context","strapi","requestContext","get","request","url","startsWith","action","endsWith","contentType","uid","getSchemas","attributesSchema","getModel","attributes","componentsSchemas","Object","keys","reduce","currentComponentSchemas","key","fieldSchema","type","componentSchema","component","schema","omit","FIELDS_TO_IGNORE","createLifecyclesService","state","isInitialized","serviceUtils","createServiceUtils","persistTablesWithPrefix","service","bootstrap","documents","use","next","result","documentId","params","defaultLocale","getDefaultLocale","locales","castArray","locale","length","schemas","model","isLocalizedContentType","localeEntries","db","query","findMany","where","$in","contentTypes","hasDraftAndPublish","publishedAt","populate","getDeepPopulate","transaction","onCommit","entry","status","getVersionStatus","getService","createVersion","data","relatedDocumentId","cron","add","deleteHistoryDaily","task","retentionDaysInMilliseconds","getRetentionDays","expirationDate","Date","now","HISTORY_VERSION_UID","deleteMany","created_at","$lt","catch","error","Error","log","message","options","destroy","remove"],"mappings":";;;;;;AAWA;;IAGA,MAAMA,6BAA6B,CACjCC,OAAAA,GAAAA;;IAMA,IAAI,CAACC,OAAOC,cAAc,CAACC,GAAG,EAAIC,EAAAA,OAAAA,CAAQC,GAAIC,CAAAA,UAAAA,CAAW,kBAAqB,CAAA,EAAA;QAC5E,OAAO,KAAA;AACT;;IAGA,IACEN,OAAAA,CAAQO,MAAM,KAAK,QAAA,IACnBP,QAAQO,MAAM,KAAK,QACnBP,IAAAA,OAAAA,C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AA,CAAA;gBAEA,OAAOT,MAAAA;AACT,aAAA,CAAA;;YAGAtC,OAAOsE,CAAAA,IAAI,CAACC,GAAG,CAAC;gBACdC,kBAAoB,EAAA;oBAClB,MAAMC,IAAAA,CAAAA,GAAAA;AACJ,wBAAA,MAAMC,8BACJ5C,YAAa6C,CAAAA,gBAAgB,EAAK,GAAA,EAAA,GAAK,KAAK,EAAK,GAAA,IAAA;AACnD,wBAAA,MAAMC,cAAiB,GAAA,IAAIC,IAAKA,CAAAA,IAAAA,CAAKC,GAAG,EAAKJ,GAAAA,2BAAAA,CAAAA;AAE7C1E,wBAAAA,OAAAA,CAAOmD,EAAE,CACNC,KAAK,CAAC2B,mBAAAA,CAAAA,CACNC,UAAU,CAAC;4BACV1B,KAAO,EAAA;gCACL2B,UAAY,EAAA;oCACVC,GAAKN,EAAAA;AACP;AACF;yBAEDO,CAAAA,CAAAA,KAAK,CAAC,CAACC,KAAAA,GAAAA;AACN,4BAAA,IAAIA,iBAAiBC,KAAO,EAAA;AAC1BrF,gCAAAA,OAAAA,CAAOsF,GAAG,CAACF,KAAK,CAAC,yCAAA,EAA2CA,MAAMG,OAAO,CAAA;AAC3E;AACF,yBAAA,CAAA;AACJ,qBAAA;oBACAC,OAAS,EAAA;AACX;AACF,aAAA,CAAA;AAEA5D,YAAAA,KAAAA,CAAMC,aAAa,GAAG,IAAA;AACxB,SAAA;QAEA,MAAM4D,OAAAA,CAAAA,GAAAA;YACJzF,OAAOsE,CAAAA,IAAI,CAACoB,MAAM,CAAC,oBAAA,CAAA;AACrB;AACF,KAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"homepage.js","sources":["../../../../server/src/homepage/controllers/homepage.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\nimport * as yup from 'yup';\nimport { errors } from '@strapi/utils';\nimport type { GetRecentDocuments } from '../../../../shared/contracts/homepage';\n\nconst createHomepageController = () => {\n const homepageService = strapi.plugin('content-manager').service('homepage');\n\n const recentDocumentParamsSchema = yup.object().shape({\n action: yup\n .mixed<GetRecentDocuments.Request['query']['action']>()\n .oneOf(['update', 'publish'])\n .required(),\n });\n\n return {\n async getRecentDocuments(ctx): Promise<GetRecentDocuments.Response> {\n let action;\n\n try {\n action = (await recentDocumentParamsSchema.validate(ctx.query)).action;\n } catch (error) {\n if (error instanceof yup.ValidationError) {\n throw new errors.ValidationError(error.message);\n }\n throw error;\n }\n\n if (action === 'publish') {\n return { data: await homepageService.getRecentlyPublishedDocuments() };\n }\n\n return { data: await homepageService.getRecentlyUpdatedDocuments() };\n },\n } satisfies Core.Controller;\n};\n\nexport { createHomepageController };\n"],"names":["createHomepageController","homepageService","strapi","plugin","service","recentDocumentParamsSchema","yup","object","shape","action","mixed","oneOf","required","getRecentDocuments","ctx","validate","query","error","ValidationError","errors","message","data","getRecentlyPublishedDocuments","getRecentlyUpdatedDocuments"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAMA,wBAA2B,GAAA,IAAA;AAC/B,IAAA,MAAMC,kBAAkBC,MAAOC,CAAAA,MAAM,CAAC,iBAAA,CAAA,CAAmBC,OAAO,CAAC,UAAA,CAAA;AAEjE,IAAA,MAAMC,0BAA6BC,GAAAA,cAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACpDC,QAAAA,MAAAA,EAAQH,cACLI,CAAAA,KAAK,EACLC,CAAAA,KAAK,CAAC;AAAC,YAAA,QAAA;AAAU,YAAA;AAAU,SAAA,CAAA,CAC3BC,QAAQ;AACb,KAAA,CAAA;IAEA,OAAO;AACL,QAAA,MAAMC,oBAAmBC,GAAG,EAAA;YAC1B,IAAIL,MAAAA;YAEJ,IAAI;gBACFA,MAAS,GAAC,CAAA,MAAMJ,0BAA2BU,CAAAA,QAAQ,CAACD,GAAIE,CAAAA,KAAK,CAAA,EAAGP,MAAM;AACxE,aAAA,CAAE,OAAOQ,KAAO,EAAA;gBACd,IAAIA,KAAAA,YAAiBX,cAAIY,CAAAA,eAAe,EAAE;AACxC,oBAAA,MAAM,IAAIC,kBAAAA,CAAOD,eAAe,CAACD,MAAMG,OAAO,CAAA;AAChD;gBACA,MAAMH,KAAAA;AACR;AAEA,YAAA,IAAIR,WAAW,SAAW,EAAA;gBACxB,OAAO;oBAAEY,IAAM,EAAA,MAAMpB,gBAAgBqB,6BAA6B;AAAG,iBAAA;AACvE;YAEA,OAAO;gBAAED,IAAM,EAAA,MAAMpB,gBAAgBsB,2BAA2B;AAAG,aAAA;AACrE;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"homepage.js","sources":["../../../../server/src/homepage/controllers/homepage.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\nimport * as yup from 'yup';\nimport { errors } from '@strapi/utils';\nimport type { GetRecentDocuments, GetCountDocuments } from '../../../../shared/contracts/homepage';\n\nconst createHomepageController = () => {\n const homepageService = strapi.plugin('content-manager').service('homepage');\n\n const recentDocumentParamsSchema = yup.object().shape({\n action: yup\n .mixed<GetRecentDocuments.Request['query']['action']>()\n .oneOf(['update', 'publish'])\n .required(),\n });\n\n return {\n async getRecentDocuments(ctx): Promise<GetRecentDocuments.Response> {\n let action;\n\n try {\n action = (await recentDocumentParamsSchema.validate(ctx.query)).action;\n } catch (error) {\n if (error instanceof yup.ValidationError) {\n throw new errors.ValidationError(error.message);\n }\n throw error;\n }\n\n if (action === 'publish') {\n return { data: await homepageService.getRecentlyPublishedDocuments() };\n }\n\n return { data: await homepageService.getRecentlyUpdatedDocuments() };\n },\n async getCountDocuments(): Promise<GetCountDocuments.Response> {\n return { data: await homepageService.getCountDocuments() };\n },\n } satisfies Core.Controller;\n};\n\nexport { createHomepageController };\n"],"names":["createHomepageController","homepageService","strapi","plugin","service","recentDocumentParamsSchema","yup","object","shape","action","mixed","oneOf","required","getRecentDocuments","ctx","validate","query","error","ValidationError","errors","message","data","getRecentlyPublishedDocuments","getRecentlyUpdatedDocuments","getCountDocuments"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAMA,wBAA2B,GAAA,IAAA;AAC/B,IAAA,MAAMC,kBAAkBC,MAAOC,CAAAA,MAAM,CAAC,iBAAA,CAAA,CAAmBC,OAAO,CAAC,UAAA,CAAA;AAEjE,IAAA,MAAMC,0BAA6BC,GAAAA,cAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACpDC,QAAAA,MAAAA,EAAQH,cACLI,CAAAA,KAAK,EACLC,CAAAA,KAAK,CAAC;AAAC,YAAA,QAAA;AAAU,YAAA;AAAU,SAAA,CAAA,CAC3BC,QAAQ;AACb,KAAA,CAAA;IAEA,OAAO;AACL,QAAA,MAAMC,oBAAmBC,GAAG,EAAA;YAC1B,IAAIL,MAAAA;YAEJ,IAAI;gBACFA,MAAS,GAAC,CAAA,MAAMJ,0BAA2BU,CAAAA,QAAQ,CAACD,GAAIE,CAAAA,KAAK,CAAA,EAAGP,MAAM;AACxE,aAAA,CAAE,OAAOQ,KAAO,EAAA;gBACd,IAAIA,KAAAA,YAAiBX,cAAIY,CAAAA,eAAe,EAAE;AACxC,oBAAA,MAAM,IAAIC,kBAAAA,CAAOD,eAAe,CAACD,MAAMG,OAAO,CAAA;AAChD;gBACA,MAAMH,KAAAA;AACR;AAEA,YAAA,IAAIR,WAAW,SAAW,EAAA;gBACxB,OAAO;oBAAEY,IAAM,EAAA,MAAMpB,gBAAgBqB,6BAA6B;AAAG,iBAAA;AACvE;YAEA,OAAO;gBAAED,IAAM,EAAA,MAAMpB,gBAAgBsB,2BAA2B;AAAG,aAAA;AACrE,SAAA;QACA,MAAMC,iBAAAA,CAAAA,GAAAA;YACJ,OAAO;gBAAEH,IAAM,EAAA,MAAMpB,gBAAgBuB,iBAAiB;AAAG,aAAA;AAC3D;AACF,KAAA;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"homepage.mjs","sources":["../../../../server/src/homepage/controllers/homepage.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\nimport * as yup from 'yup';\nimport { errors } from '@strapi/utils';\nimport type { GetRecentDocuments } from '../../../../shared/contracts/homepage';\n\nconst createHomepageController = () => {\n const homepageService = strapi.plugin('content-manager').service('homepage');\n\n const recentDocumentParamsSchema = yup.object().shape({\n action: yup\n .mixed<GetRecentDocuments.Request['query']['action']>()\n .oneOf(['update', 'publish'])\n .required(),\n });\n\n return {\n async getRecentDocuments(ctx): Promise<GetRecentDocuments.Response> {\n let action;\n\n try {\n action = (await recentDocumentParamsSchema.validate(ctx.query)).action;\n } catch (error) {\n if (error instanceof yup.ValidationError) {\n throw new errors.ValidationError(error.message);\n }\n throw error;\n }\n\n if (action === 'publish') {\n return { data: await homepageService.getRecentlyPublishedDocuments() };\n }\n\n return { data: await homepageService.getRecentlyUpdatedDocuments() };\n },\n } satisfies Core.Controller;\n};\n\nexport { createHomepageController };\n"],"names":["createHomepageController","homepageService","strapi","plugin","service","recentDocumentParamsSchema","yup","object","shape","action","mixed","oneOf","required","getRecentDocuments","ctx","validate","query","error","ValidationError","errors","message","data","getRecentlyPublishedDocuments","getRecentlyUpdatedDocuments"],"mappings":";;;AAKA,MAAMA,wBAA2B,GAAA,IAAA;AAC/B,IAAA,MAAMC,kBAAkBC,MAAOC,CAAAA,MAAM,CAAC,iBAAA,CAAA,CAAmBC,OAAO,CAAC,UAAA,CAAA;AAEjE,IAAA,MAAMC,0BAA6BC,GAAAA,GAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACpDC,QAAAA,MAAAA,EAAQH,GACLI,CAAAA,KAAK,EACLC,CAAAA,KAAK,CAAC;AAAC,YAAA,QAAA;AAAU,YAAA;AAAU,SAAA,CAAA,CAC3BC,QAAQ;AACb,KAAA,CAAA;IAEA,OAAO;AACL,QAAA,MAAMC,oBAAmBC,GAAG,EAAA;YAC1B,IAAIL,MAAAA;YAEJ,IAAI;gBACFA,MAAS,GAAC,CAAA,MAAMJ,0BAA2BU,CAAAA,QAAQ,CAACD,GAAIE,CAAAA,KAAK,CAAA,EAAGP,MAAM;AACxE,aAAA,CAAE,OAAOQ,KAAO,EAAA;gBACd,IAAIA,KAAAA,YAAiBX,GAAIY,CAAAA,eAAe,EAAE;AACxC,oBAAA,MAAM,IAAIC,MAAAA,CAAOD,eAAe,CAACD,MAAMG,OAAO,CAAA;AAChD;gBACA,MAAMH,KAAAA;AACR;AAEA,YAAA,IAAIR,WAAW,SAAW,EAAA;gBACxB,OAAO;oBAAEY,IAAM,EAAA,MAAMpB,gBAAgBqB,6BAA6B;AAAG,iBAAA;AACvE;YAEA,OAAO;gBAAED,IAAM,EAAA,MAAMpB,gBAAgBsB,2BAA2B;AAAG,aAAA;AACrE;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"homepage.mjs","sources":["../../../../server/src/homepage/controllers/homepage.ts"],"sourcesContent":["import type { Core } from '@strapi/types';\nimport * as yup from 'yup';\nimport { errors } from '@strapi/utils';\nimport type { GetRecentDocuments, GetCountDocuments } from '../../../../shared/contracts/homepage';\n\nconst createHomepageController = () => {\n const homepageService = strapi.plugin('content-manager').service('homepage');\n\n const recentDocumentParamsSchema = yup.object().shape({\n action: yup\n .mixed<GetRecentDocuments.Request['query']['action']>()\n .oneOf(['update', 'publish'])\n .required(),\n });\n\n return {\n async getRecentDocuments(ctx): Promise<GetRecentDocuments.Response> {\n let action;\n\n try {\n action = (await recentDocumentParamsSchema.validate(ctx.query)).action;\n } catch (error) {\n if (error instanceof yup.ValidationError) {\n throw new errors.ValidationError(error.message);\n }\n throw error;\n }\n\n if (action === 'publish') {\n return { data: await homepageService.getRecentlyPublishedDocuments() };\n }\n\n return { data: await homepageService.getRecentlyUpdatedDocuments() };\n },\n async getCountDocuments(): Promise<GetCountDocuments.Response> {\n return { data: await homepageService.getCountDocuments() };\n },\n } satisfies Core.Controller;\n};\n\nexport { createHomepageController };\n"],"names":["createHomepageController","homepageService","strapi","plugin","service","recentDocumentParamsSchema","yup","object","shape","action","mixed","oneOf","required","getRecentDocuments","ctx","validate","query","error","ValidationError","errors","message","data","getRecentlyPublishedDocuments","getRecentlyUpdatedDocuments","getCountDocuments"],"mappings":";;;AAKA,MAAMA,wBAA2B,GAAA,IAAA;AAC/B,IAAA,MAAMC,kBAAkBC,MAAOC,CAAAA,MAAM,CAAC,iBAAA,CAAA,CAAmBC,OAAO,CAAC,UAAA,CAAA;AAEjE,IAAA,MAAMC,0BAA6BC,GAAAA,GAAAA,CAAIC,MAAM,EAAA,CAAGC,KAAK,CAAC;AACpDC,QAAAA,MAAAA,EAAQH,GACLI,CAAAA,KAAK,EACLC,CAAAA,KAAK,CAAC;AAAC,YAAA,QAAA;AAAU,YAAA;AAAU,SAAA,CAAA,CAC3BC,QAAQ;AACb,KAAA,CAAA;IAEA,OAAO;AACL,QAAA,MAAMC,oBAAmBC,GAAG,EAAA;YAC1B,IAAIL,MAAAA;YAEJ,IAAI;gBACFA,MAAS,GAAC,CAAA,MAAMJ,0BAA2BU,CAAAA,QAAQ,CAACD,GAAIE,CAAAA,KAAK,CAAA,EAAGP,MAAM;AACxE,aAAA,CAAE,OAAOQ,KAAO,EAAA;gBACd,IAAIA,KAAAA,YAAiBX,GAAIY,CAAAA,eAAe,EAAE;AACxC,oBAAA,MAAM,IAAIC,MAAAA,CAAOD,eAAe,CAACD,MAAMG,OAAO,CAAA;AAChD;gBACA,MAAMH,KAAAA;AACR;AAEA,YAAA,IAAIR,WAAW,SAAW,EAAA;gBACxB,OAAO;oBAAEY,IAAM,EAAA,MAAMpB,gBAAgBqB,6BAA6B;AAAG,iBAAA;AACvE;YAEA,OAAO;gBAAED,IAAM,EAAA,MAAMpB,gBAAgBsB,2BAA2B;AAAG,aAAA;AACrE,SAAA;QACA,MAAMC,iBAAAA,CAAAA,GAAAA;YACJ,OAAO;gBAAEH,IAAM,EAAA,MAAMpB,gBAAgBuB,iBAAiB;AAAG,aAAA;AAC3D;AACF,KAAA;AACF;;;;"}
|
|
@@ -17,6 +17,17 @@ const homepageRouter = {
|
|
|
17
17
|
'admin::isAuthenticatedAdmin'
|
|
18
18
|
]
|
|
19
19
|
}
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
method: 'GET',
|
|
23
|
+
info,
|
|
24
|
+
path: '/homepage/count-documents',
|
|
25
|
+
handler: 'homepage.getCountDocuments',
|
|
26
|
+
config: {
|
|
27
|
+
policies: [
|
|
28
|
+
'admin::isAuthenticatedAdmin'
|
|
29
|
+
]
|
|
30
|
+
}
|
|
20
31
|
}
|
|
21
32
|
]
|
|
22
33
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"homepage.js","sources":["../../../../server/src/homepage/routes/homepage.ts"],"sourcesContent":["import type { Plugin } from '@strapi/types';\n\nconst info = { pluginName: 'content-manager', type: 'admin' };\n\nconst homepageRouter: Plugin.LoadedPlugin['routes'][string] = {\n type: 'admin',\n routes: [\n {\n method: 'GET',\n info,\n path: '/homepage/recent-documents',\n handler: 'homepage.getRecentDocuments',\n config: {\n policies: ['admin::isAuthenticatedAdmin'],\n },\n },\n ],\n};\n\nexport { homepageRouter };\n"],"names":["info","pluginName","type","homepageRouter","routes","method","path","handler","config","policies"],"mappings":";;AAEA,MAAMA,IAAO,GAAA;IAAEC,UAAY,EAAA,iBAAA;IAAmBC,IAAM,EAAA;AAAQ,CAAA;AAE5D,MAAMC,cAAwD,GAAA;IAC5DD,IAAM,EAAA,OAAA;IACNE,MAAQ,EAAA;AACN,QAAA;YACEC,MAAQ,EAAA,KAAA;AACRL,YAAAA,IAAAA;YACAM,IAAM,EAAA,4BAAA;YACNC,OAAS,EAAA,6BAAA;YACTC,MAAQ,EAAA;gBACNC,QAAU,EAAA;AAAC,oBAAA;AAA8B;AAC3C;AACF;AACD;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"homepage.js","sources":["../../../../server/src/homepage/routes/homepage.ts"],"sourcesContent":["import type { Plugin } from '@strapi/types';\n\nconst info = { pluginName: 'content-manager', type: 'admin' };\n\nconst homepageRouter: Plugin.LoadedPlugin['routes'][string] = {\n type: 'admin',\n routes: [\n {\n method: 'GET',\n info,\n path: '/homepage/recent-documents',\n handler: 'homepage.getRecentDocuments',\n config: {\n policies: ['admin::isAuthenticatedAdmin'],\n },\n },\n {\n method: 'GET',\n info,\n path: '/homepage/count-documents',\n handler: 'homepage.getCountDocuments',\n config: {\n policies: ['admin::isAuthenticatedAdmin'],\n },\n },\n ],\n};\n\nexport { homepageRouter };\n"],"names":["info","pluginName","type","homepageRouter","routes","method","path","handler","config","policies"],"mappings":";;AAEA,MAAMA,IAAO,GAAA;IAAEC,UAAY,EAAA,iBAAA;IAAmBC,IAAM,EAAA;AAAQ,CAAA;AAE5D,MAAMC,cAAwD,GAAA;IAC5DD,IAAM,EAAA,OAAA;IACNE,MAAQ,EAAA;AACN,QAAA;YACEC,MAAQ,EAAA,KAAA;AACRL,YAAAA,IAAAA;YACAM,IAAM,EAAA,4BAAA;YACNC,OAAS,EAAA,6BAAA;YACTC,MAAQ,EAAA;gBACNC,QAAU,EAAA;AAAC,oBAAA;AAA8B;AAC3C;AACF,SAAA;AACA,QAAA;YACEJ,MAAQ,EAAA,KAAA;AACRL,YAAAA,IAAAA;YACAM,IAAM,EAAA,2BAAA;YACNC,OAAS,EAAA,4BAAA;YACTC,MAAQ,EAAA;gBACNC,QAAU,EAAA;AAAC,oBAAA;AAA8B;AAC3C;AACF;AACD;AACH;;;;"}
|
|
@@ -15,6 +15,17 @@ const homepageRouter = {
|
|
|
15
15
|
'admin::isAuthenticatedAdmin'
|
|
16
16
|
]
|
|
17
17
|
}
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
method: 'GET',
|
|
21
|
+
info,
|
|
22
|
+
path: '/homepage/count-documents',
|
|
23
|
+
handler: 'homepage.getCountDocuments',
|
|
24
|
+
config: {
|
|
25
|
+
policies: [
|
|
26
|
+
'admin::isAuthenticatedAdmin'
|
|
27
|
+
]
|
|
28
|
+
}
|
|
18
29
|
}
|
|
19
30
|
]
|
|
20
31
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"homepage.mjs","sources":["../../../../server/src/homepage/routes/homepage.ts"],"sourcesContent":["import type { Plugin } from '@strapi/types';\n\nconst info = { pluginName: 'content-manager', type: 'admin' };\n\nconst homepageRouter: Plugin.LoadedPlugin['routes'][string] = {\n type: 'admin',\n routes: [\n {\n method: 'GET',\n info,\n path: '/homepage/recent-documents',\n handler: 'homepage.getRecentDocuments',\n config: {\n policies: ['admin::isAuthenticatedAdmin'],\n },\n },\n ],\n};\n\nexport { homepageRouter };\n"],"names":["info","pluginName","type","homepageRouter","routes","method","path","handler","config","policies"],"mappings":"AAEA,MAAMA,IAAO,GAAA;IAAEC,UAAY,EAAA,iBAAA;IAAmBC,IAAM,EAAA;AAAQ,CAAA;AAE5D,MAAMC,cAAwD,GAAA;IAC5DD,IAAM,EAAA,OAAA;IACNE,MAAQ,EAAA;AACN,QAAA;YACEC,MAAQ,EAAA,KAAA;AACRL,YAAAA,IAAAA;YACAM,IAAM,EAAA,4BAAA;YACNC,OAAS,EAAA,6BAAA;YACTC,MAAQ,EAAA;gBACNC,QAAU,EAAA;AAAC,oBAAA;AAA8B;AAC3C;AACF;AACD;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"homepage.mjs","sources":["../../../../server/src/homepage/routes/homepage.ts"],"sourcesContent":["import type { Plugin } from '@strapi/types';\n\nconst info = { pluginName: 'content-manager', type: 'admin' };\n\nconst homepageRouter: Plugin.LoadedPlugin['routes'][string] = {\n type: 'admin',\n routes: [\n {\n method: 'GET',\n info,\n path: '/homepage/recent-documents',\n handler: 'homepage.getRecentDocuments',\n config: {\n policies: ['admin::isAuthenticatedAdmin'],\n },\n },\n {\n method: 'GET',\n info,\n path: '/homepage/count-documents',\n handler: 'homepage.getCountDocuments',\n config: {\n policies: ['admin::isAuthenticatedAdmin'],\n },\n },\n ],\n};\n\nexport { homepageRouter };\n"],"names":["info","pluginName","type","homepageRouter","routes","method","path","handler","config","policies"],"mappings":"AAEA,MAAMA,IAAO,GAAA;IAAEC,UAAY,EAAA,iBAAA;IAAmBC,IAAM,EAAA;AAAQ,CAAA;AAE5D,MAAMC,cAAwD,GAAA;IAC5DD,IAAM,EAAA,OAAA;IACNE,MAAQ,EAAA;AACN,QAAA;YACEC,MAAQ,EAAA,KAAA;AACRL,YAAAA,IAAAA;YACAM,IAAM,EAAA,4BAAA;YACNC,OAAS,EAAA,6BAAA;YACTC,MAAQ,EAAA;gBACNC,QAAU,EAAA;AAAC,oBAAA;AAA8B;AAC3C;AACF,SAAA;AACA,QAAA;YACEJ,MAAQ,EAAA,KAAA;AACRL,YAAAA,IAAAA;YACAM,IAAM,EAAA,2BAAA;YACNC,OAAS,EAAA,4BAAA;YACTC,MAAQ,EAAA;gBACNC,QAAU,EAAA;AAAC,oBAAA;AAA8B;AAC3C;AACF;AACD;AACH;;;;"}
|
|
@@ -158,6 +158,37 @@ const createHomepageService = ({ strapi })=>{
|
|
|
158
158
|
sort: 'updatedAt:desc'
|
|
159
159
|
});
|
|
160
160
|
return this.addStatusToDocuments(recentlyUpdatedDocuments);
|
|
161
|
+
},
|
|
162
|
+
async getCountDocuments () {
|
|
163
|
+
const permittedContentTypes = await getPermittedContentTypes();
|
|
164
|
+
// Fetch the configuration for each content type in a single query
|
|
165
|
+
const configurations = await getConfiguration(permittedContentTypes);
|
|
166
|
+
// Get the necessary metadata for the documents
|
|
167
|
+
const contentTypesMeta = getContentTypesMeta(permittedContentTypes, configurations);
|
|
168
|
+
const countDocuments = {
|
|
169
|
+
draft: 0,
|
|
170
|
+
published: 0,
|
|
171
|
+
modified: 0
|
|
172
|
+
};
|
|
173
|
+
await Promise.all(contentTypesMeta.map(async (meta)=>{
|
|
174
|
+
const strapiDBConnection = strapi.db.connection;
|
|
175
|
+
const tableName = strapi.contentType(meta.uid).collectionName;
|
|
176
|
+
if (tableName) {
|
|
177
|
+
const draftDocuments = await strapiDBConnection(tableName).whereNull('published_at').whereIn('document_id', function() {
|
|
178
|
+
this.select('document_id').from(tableName).groupBy('document_id').havingRaw('COUNT(*) = 1');
|
|
179
|
+
}).count('* as count').first();
|
|
180
|
+
countDocuments.draft += Number(draftDocuments?.count) || 0;
|
|
181
|
+
const publishedDocuments = meta.hasDraftAndPublish ? await strapiDBConnection(tableName).countDistinct('draft.document_id as count').from(`${tableName} as draft`).join(`${tableName} as published`, function() {
|
|
182
|
+
this.on('draft.document_id', '=', 'published.document_id').andOn('draft.updated_at', '=', 'published.updated_at').andOnNull('draft.published_at').andOnNotNull('published.published_at');
|
|
183
|
+
}).first() : await strapiDBConnection(tableName).select('document_id').from(`${tableName}`).countDistinct('document_id as count').groupBy('document_id').first();
|
|
184
|
+
countDocuments.published += Number(publishedDocuments?.count) || 0;
|
|
185
|
+
const modifiedDocuments = await strapiDBConnection(tableName).select('draft.document_id').from(`${tableName} as draft`).join(`${tableName} as published`, function() {
|
|
186
|
+
this.on('draft.document_id', '=', 'published.document_id').andOn('draft.updated_at', '!=', 'published.updated_at').andOnNull('draft.published_at').andOnNotNull('published.published_at');
|
|
187
|
+
}).countDistinct('draft.document_id as count').groupBy('draft.document_id').first();
|
|
188
|
+
countDocuments.modified += Number(modifiedDocuments?.count) || 0;
|
|
189
|
+
}
|
|
190
|
+
}));
|
|
191
|
+
return countDocuments;
|
|
161
192
|
}
|
|
162
193
|
};
|
|
163
194
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"homepage.js","sources":["../../../../server/src/homepage/services/homepage.ts"],"sourcesContent":["import type { Core, Modules, Schema } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport type { GetRecentDocuments, RecentDocument } from '../../../../shared/contracts/homepage';\n\nconst createHomepageService = ({ strapi }: { strapi: Core.Strapi }) => {\n const MAX_DOCUMENTS = 4;\n\n const metadataService = strapi.plugin('content-manager').service('document-metadata');\n const permissionService = strapi.admin.services.permission;\n\n type ContentTypeConfiguration = {\n uid: RecentDocument['contentTypeUid'];\n settings: { mainField: string };\n };\n const getConfiguration = async (\n contentTypeUids: RecentDocument['contentTypeUid'][]\n ): Promise<ContentTypeConfiguration[]> => {\n /**\n * Don't use the strapi.store util because we need to make\n * more precise queries than exact key matches, in order to make as few queries as possible.\n */\n const coreStore = strapi.db.query('strapi::core-store');\n const rawConfigurations = await coreStore.findMany({\n where: {\n key: {\n $in: contentTypeUids.map(\n (contentType) => `plugin_content_manager_configuration_content_types::${contentType}`\n ),\n },\n },\n });\n\n return rawConfigurations.map((rawConfiguration) => {\n return JSON.parse(rawConfiguration.value);\n });\n };\n\n const getPermittedContentTypes = async () => {\n const readPermissions: Modules.Permissions.PermissionRule[] = await permissionService.findMany({\n where: {\n role: { users: { id: strapi.requestContext.get()?.state?.user.id } },\n action: 'plugin::content-manager.explorer.read',\n },\n });\n\n return readPermissions\n .map((permission) => permission.subject)\n .filter(Boolean) as RecentDocument['contentTypeUid'][];\n };\n\n type ContentTypeMeta = {\n fields: string[];\n mainField: string;\n contentType: Schema.ContentType;\n hasDraftAndPublish: boolean;\n uid: RecentDocument['contentTypeUid'];\n };\n\n const getContentTypesMeta = (\n allowedContentTypeUids: RecentDocument['contentTypeUid'][],\n configurations: ContentTypeConfiguration[]\n ): ContentTypeMeta[] => {\n return allowedContentTypeUids.map((uid) => {\n const configuration = configurations.find((config) => config.uid === uid);\n const contentType = strapi.contentType(uid);\n const fields = ['documentId', 'updatedAt'];\n\n // Add fields required to get the status if D&P is enabled\n const hasDraftAndPublish = contentTypes.hasDraftAndPublish(contentType);\n if (hasDraftAndPublish) {\n fields.push('publishedAt');\n }\n\n // Only add the main field if it's defined\n if (configuration?.settings.mainField) {\n fields.push(configuration.settings.mainField);\n }\n\n // Only add locale if it's localized\n const isLocalized = (contentType.pluginOptions?.i18n as any)?.localized;\n if (isLocalized) {\n fields.push('locale');\n }\n\n return {\n fields,\n mainField: configuration!.settings.mainField,\n contentType,\n hasDraftAndPublish,\n uid,\n };\n });\n };\n\n const formatDocuments = (\n documents: Modules.Documents.AnyDocument[],\n meta: ContentTypeMeta,\n populate?: string[]\n ) => {\n return documents.map((document) => {\n const additionalFields =\n populate?.reduce(\n (acc, key) => {\n acc[key] = document[key];\n return acc;\n },\n {} as Record<string, any>\n ) || {};\n return {\n documentId: document.documentId,\n locale: document.locale ?? null,\n updatedAt: new Date(document.updatedAt),\n title: document[meta.mainField ?? 'documentId'],\n publishedAt:\n meta.hasDraftAndPublish && document.publishedAt ? new Date(document.publishedAt) : null,\n contentTypeUid: meta.uid,\n contentTypeDisplayName: meta.contentType.info.displayName,\n kind: meta.contentType.kind,\n ...additionalFields,\n };\n });\n };\n\n const permissionCheckerService = strapi.plugin('content-manager').service('permission-checker');\n const getPermissionChecker = (uid: string) =>\n permissionCheckerService.create({\n userAbility: strapi.requestContext.get()?.state.userAbility,\n model: uid,\n });\n\n return {\n async addStatusToDocuments(documents: RecentDocument[]): Promise<RecentDocument[]> {\n return Promise.all(\n documents.map(async (recentDocument) => {\n const hasDraftAndPublish = contentTypes.hasDraftAndPublish(\n strapi.contentType(recentDocument.contentTypeUid)\n );\n /**\n * Tries to query the other version of the document if draft and publish is enabled,\n * so that we know when to give the \"modified\" status.\n */\n const { availableStatus } = await metadataService.getMetadata(\n recentDocument.contentTypeUid,\n recentDocument,\n {\n availableStatus: hasDraftAndPublish,\n availableLocales: false,\n }\n );\n const status: RecentDocument['status'] = metadataService.getStatus(\n recentDocument,\n availableStatus\n );\n\n return {\n ...recentDocument,\n status: hasDraftAndPublish ? status : undefined,\n };\n })\n );\n },\n\n async queryLastDocuments(\n additionalQueryParams?: Record<string, unknown>,\n draftAndPublishOnly?: boolean\n ): Promise<RecentDocument[]> {\n const permittedContentTypes = await getPermittedContentTypes();\n const allowedContentTypeUids = draftAndPublishOnly\n ? permittedContentTypes.filter((uid) => {\n return contentTypes.hasDraftAndPublish(strapi.contentType(uid));\n })\n : permittedContentTypes;\n // Fetch the configuration for each content type in a single query\n const configurations = await getConfiguration(allowedContentTypeUids);\n // Get the necessary metadata for the documents\n const contentTypesMeta = getContentTypesMeta(allowedContentTypeUids, configurations);\n\n const recentDocuments = await Promise.all(\n contentTypesMeta.map(async (meta) => {\n const permissionQuery = await getPermissionChecker(meta.uid).sanitizedQuery.read({\n limit: MAX_DOCUMENTS,\n fields: meta.fields,\n ...additionalQueryParams,\n });\n\n const docs = await strapi.documents(meta.uid).findMany(permissionQuery);\n const populate = additionalQueryParams?.populate as string[];\n\n return formatDocuments(docs, meta, populate);\n })\n );\n\n return recentDocuments\n .flat()\n .sort((a, b) => {\n switch (additionalQueryParams?.sort) {\n case 'publishedAt:desc':\n if (!a.publishedAt || !b.publishedAt) return 0;\n return b.publishedAt.valueOf() - a.publishedAt.valueOf();\n case 'publishedAt:asc':\n if (!a.publishedAt || !b.publishedAt) return 0;\n return a.publishedAt.valueOf() - b.publishedAt.valueOf();\n case 'updatedAt:desc':\n if (!a.updatedAt || !b.updatedAt) return 0;\n return b.updatedAt.valueOf() - a.updatedAt.valueOf();\n case 'updatedAt:asc':\n if (!a.updatedAt || !b.updatedAt) return 0;\n return a.updatedAt.valueOf() - b.updatedAt.valueOf();\n default:\n return 0;\n }\n })\n .slice(0, MAX_DOCUMENTS);\n },\n\n async getRecentlyPublishedDocuments(): Promise<GetRecentDocuments.Response['data']> {\n const recentlyPublishedDocuments = await this.queryLastDocuments(\n {\n sort: 'publishedAt:desc',\n status: 'published',\n },\n true\n );\n\n return this.addStatusToDocuments(recentlyPublishedDocuments);\n },\n\n async getRecentlyUpdatedDocuments(): Promise<GetRecentDocuments.Response['data']> {\n const recentlyUpdatedDocuments = await this.queryLastDocuments({\n sort: 'updatedAt:desc',\n });\n\n return this.addStatusToDocuments(recentlyUpdatedDocuments);\n },\n };\n};\n\nexport { createHomepageService };\n"],"names":["createHomepageService","strapi","MAX_DOCUMENTS","metadataService","plugin","service","permissionService","admin","services","permission","getConfiguration","contentTypeUids","coreStore","db","query","rawConfigurations","findMany","where","key","$in","map","contentType","rawConfiguration","JSON","parse","value","getPermittedContentTypes","readPermissions","role","users","id","requestContext","get","state","user","action","subject","filter","Boolean","getContentTypesMeta","allowedContentTypeUids","configurations","uid","configuration","find","config","fields","hasDraftAndPublish","contentTypes","push","settings","mainField","isLocalized","pluginOptions","i18n","localized","formatDocuments","documents","meta","populate","document","additionalFields","reduce","acc","documentId","locale","updatedAt","Date","title","publishedAt","contentTypeUid","contentTypeDisplayName","info","displayName","kind","permissionCheckerService","getPermissionChecker","create","userAbility","model","addStatusToDocuments","Promise","all","recentDocument","availableStatus","getMetadata","availableLocales","status","getStatus","undefined","queryLastDocuments","additionalQueryParams","draftAndPublishOnly","permittedContentTypes","contentTypesMeta","recentDocuments","permissionQuery","sanitizedQuery","read","limit","docs","flat","sort","a","b","valueOf","slice","getRecentlyPublishedDocuments","recentlyPublishedDocuments","getRecentlyUpdatedDocuments","recentlyUpdatedDocuments"],"mappings":";;;;AAKA,MAAMA,qBAAwB,GAAA,CAAC,EAAEC,MAAM,EAA2B,GAAA;AAChE,IAAA,MAAMC,aAAgB,GAAA,CAAA;AAEtB,IAAA,MAAMC,kBAAkBF,MAAOG,CAAAA,MAAM,CAAC,iBAAA,CAAA,CAAmBC,OAAO,CAAC,mBAAA,CAAA;AACjE,IAAA,MAAMC,oBAAoBL,MAAOM,CAAAA,KAAK,CAACC,QAAQ,CAACC,UAAU;AAM1D,IAAA,MAAMC,mBAAmB,OACvBC,eAAAA,GAAAA;AAEA;;;AAGC,QACD,MAAMC,SAAYX,GAAAA,MAAAA,CAAOY,EAAE,CAACC,KAAK,CAAC,oBAAA,CAAA;AAClC,QAAA,MAAMC,iBAAoB,GAAA,MAAMH,SAAUI,CAAAA,QAAQ,CAAC;YACjDC,KAAO,EAAA;gBACLC,GAAK,EAAA;oBACHC,GAAKR,EAAAA,eAAAA,CAAgBS,GAAG,CACtB,CAACC,cAAgB,CAAC,oDAAoD,EAAEA,WAAAA,CAAY,CAAC;AAEzF;AACF;AACF,SAAA,CAAA;QAEA,OAAON,iBAAAA,CAAkBK,GAAG,CAAC,CA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J,YAAA,MAAMC,wBAA2B,GAAA,MAAM,IAAI,CAACpB,kBAAkB,CAAC;gBAC7DY,IAAM,EAAA;AACR,aAAA,CAAA;YAEA,OAAO,IAAI,CAACtB,oBAAoB,CAAC8B,wBAAAA,CAAAA;AACnC;AACF,KAAA;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"homepage.js","sources":["../../../../server/src/homepage/services/homepage.ts"],"sourcesContent":["/* eslint-disable func-names */\nimport type { Core, Modules, Schema } from '@strapi/types';\nimport { contentTypes } from '@strapi/utils';\n\nimport type {\n GetCountDocuments,\n GetRecentDocuments,\n RecentDocument,\n} from '../../../../shared/contracts/homepage';\n\nconst createHomepageService = ({ strapi }: { strapi: Core.Strapi }) => {\n const MAX_DOCUMENTS = 4;\n\n const metadataService = strapi.plugin('content-manager').service('document-metadata');\n const permissionService = strapi.admin.services.permission;\n\n type ContentTypeConfiguration = {\n uid: RecentDocument['contentTypeUid'];\n settings: { mainField: string };\n };\n const getConfiguration = async (\n contentTypeUids: RecentDocument['contentTypeUid'][]\n ): Promise<ContentTypeConfiguration[]> => {\n /**\n * Don't use the strapi.store util because we need to make\n * more precise queries than exact key matches, in order to make as few queries as possible.\n */\n const coreStore = strapi.db.query('strapi::core-store');\n const rawConfigurations = await coreStore.findMany({\n where: {\n key: {\n $in: contentTypeUids.map(\n (contentType) => `plugin_content_manager_configuration_content_types::${contentType}`\n ),\n },\n },\n });\n\n return rawConfigurations.map((rawConfiguration) => {\n return JSON.parse(rawConfiguration.value);\n });\n };\n\n const getPermittedContentTypes = async () => {\n const readPermissions: Modules.Permissions.PermissionRule[] = await permissionService.findMany({\n where: {\n role: { users: { id: strapi.requestContext.get()?.state?.user.id } },\n action: 'plugin::content-manager.explorer.read',\n },\n });\n\n return readPermissions\n .map((permission) => permission.subject)\n .filter(Boolean) as RecentDocument['contentTypeUid'][];\n };\n\n type ContentTypeMeta = {\n fields: string[];\n mainField: string;\n contentType: Schema.ContentType;\n hasDraftAndPublish: boolean;\n uid: RecentDocument['contentTypeUid'];\n };\n\n const getContentTypesMeta = (\n allowedContentTypeUids: RecentDocument['contentTypeUid'][],\n configurations: ContentTypeConfiguration[]\n ): ContentTypeMeta[] => {\n return allowedContentTypeUids.map((uid) => {\n const configuration = configurations.find((config) => config.uid === uid);\n const contentType = strapi.contentType(uid);\n const fields = ['documentId', 'updatedAt'];\n\n // Add fields required to get the status if D&P is enabled\n const hasDraftAndPublish = contentTypes.hasDraftAndPublish(contentType);\n if (hasDraftAndPublish) {\n fields.push('publishedAt');\n }\n\n // Only add the main field if it's defined\n if (configuration?.settings.mainField) {\n fields.push(configuration.settings.mainField);\n }\n\n // Only add locale if it's localized\n const isLocalized = (contentType.pluginOptions?.i18n as any)?.localized;\n if (isLocalized) {\n fields.push('locale');\n }\n\n return {\n fields,\n mainField: configuration!.settings.mainField,\n contentType,\n hasDraftAndPublish,\n uid,\n };\n });\n };\n\n const formatDocuments = (\n documents: Modules.Documents.AnyDocument[],\n meta: ContentTypeMeta,\n populate?: string[]\n ) => {\n return documents.map((document) => {\n const additionalFields =\n populate?.reduce(\n (acc, key) => {\n acc[key] = document[key];\n return acc;\n },\n {} as Record<string, any>\n ) || {};\n return {\n documentId: document.documentId,\n locale: document.locale ?? null,\n updatedAt: new Date(document.updatedAt),\n title: document[meta.mainField ?? 'documentId'],\n publishedAt:\n meta.hasDraftAndPublish && document.publishedAt ? new Date(document.publishedAt) : null,\n contentTypeUid: meta.uid,\n contentTypeDisplayName: meta.contentType.info.displayName,\n kind: meta.contentType.kind,\n ...additionalFields,\n };\n });\n };\n\n const permissionCheckerService = strapi.plugin('content-manager').service('permission-checker');\n const getPermissionChecker = (uid: string) =>\n permissionCheckerService.create({\n userAbility: strapi.requestContext.get()?.state.userAbility,\n model: uid,\n });\n\n return {\n async addStatusToDocuments(documents: RecentDocument[]): Promise<RecentDocument[]> {\n return Promise.all(\n documents.map(async (recentDocument) => {\n const hasDraftAndPublish = contentTypes.hasDraftAndPublish(\n strapi.contentType(recentDocument.contentTypeUid)\n );\n /**\n * Tries to query the other version of the document if draft and publish is enabled,\n * so that we know when to give the \"modified\" status.\n */\n const { availableStatus } = await metadataService.getMetadata(\n recentDocument.contentTypeUid,\n recentDocument,\n {\n availableStatus: hasDraftAndPublish,\n availableLocales: false,\n }\n );\n const status: RecentDocument['status'] = metadataService.getStatus(\n recentDocument,\n availableStatus\n );\n\n return {\n ...recentDocument,\n status: hasDraftAndPublish ? status : undefined,\n };\n })\n );\n },\n\n async queryLastDocuments(\n additionalQueryParams?: Record<string, unknown>,\n draftAndPublishOnly?: boolean\n ): Promise<RecentDocument[]> {\n const permittedContentTypes = await getPermittedContentTypes();\n const allowedContentTypeUids = draftAndPublishOnly\n ? permittedContentTypes.filter((uid) => {\n return contentTypes.hasDraftAndPublish(strapi.contentType(uid));\n })\n : permittedContentTypes;\n // Fetch the configuration for each content type in a single query\n const configurations = await getConfiguration(allowedContentTypeUids);\n // Get the necessary metadata for the documents\n const contentTypesMeta = getContentTypesMeta(allowedContentTypeUids, configurations);\n\n const recentDocuments = await Promise.all(\n contentTypesMeta.map(async (meta) => {\n const permissionQuery = await getPermissionChecker(meta.uid).sanitizedQuery.read({\n limit: MAX_DOCUMENTS,\n fields: meta.fields,\n ...additionalQueryParams,\n });\n\n const docs = await strapi.documents(meta.uid).findMany(permissionQuery);\n const populate = additionalQueryParams?.populate as string[];\n\n return formatDocuments(docs, meta, populate);\n })\n );\n\n return recentDocuments\n .flat()\n .sort((a, b) => {\n switch (additionalQueryParams?.sort) {\n case 'publishedAt:desc':\n if (!a.publishedAt || !b.publishedAt) return 0;\n return b.publishedAt.valueOf() - a.publishedAt.valueOf();\n case 'publishedAt:asc':\n if (!a.publishedAt || !b.publishedAt) return 0;\n return a.publishedAt.valueOf() - b.publishedAt.valueOf();\n case 'updatedAt:desc':\n if (!a.updatedAt || !b.updatedAt) return 0;\n return b.updatedAt.valueOf() - a.updatedAt.valueOf();\n case 'updatedAt:asc':\n if (!a.updatedAt || !b.updatedAt) return 0;\n return a.updatedAt.valueOf() - b.updatedAt.valueOf();\n default:\n return 0;\n }\n })\n .slice(0, MAX_DOCUMENTS);\n },\n\n async getRecentlyPublishedDocuments(): Promise<GetRecentDocuments.Response['data']> {\n const recentlyPublishedDocuments = await this.queryLastDocuments(\n {\n sort: 'publishedAt:desc',\n status: 'published',\n },\n true\n );\n\n return this.addStatusToDocuments(recentlyPublishedDocuments);\n },\n\n async getRecentlyUpdatedDocuments(): Promise<GetRecentDocuments.Response['data']> {\n const recentlyUpdatedDocuments = await this.queryLastDocuments({\n sort: 'updatedAt:desc',\n });\n\n return this.addStatusToDocuments(recentlyUpdatedDocuments);\n },\n\n async getCountDocuments(): Promise<GetCountDocuments.Response['data']> {\n const permittedContentTypes = await getPermittedContentTypes();\n // Fetch the configuration for each content type in a single query\n const configurations = await getConfiguration(permittedContentTypes);\n // Get the necessary metadata for the documents\n const contentTypesMeta = getContentTypesMeta(permittedContentTypes, configurations);\n\n const countDocuments = {\n draft: 0,\n published: 0,\n modified: 0,\n };\n\n await Promise.all(\n contentTypesMeta.map(async (meta) => {\n const strapiDBConnection = strapi.db.connection;\n const tableName = strapi.contentType(meta.uid).collectionName;\n if (tableName) {\n const draftDocuments = await strapiDBConnection(tableName)\n .whereNull('published_at')\n .whereIn('document_id', function () {\n this.select('document_id')\n .from(tableName)\n .groupBy('document_id')\n .havingRaw('COUNT(*) = 1');\n })\n .count('* as count')\n .first();\n countDocuments.draft += Number(draftDocuments?.count) || 0;\n\n const publishedDocuments = meta.hasDraftAndPublish\n ? await strapiDBConnection(tableName)\n .countDistinct('draft.document_id as count')\n .from(`${tableName} as draft`)\n .join(`${tableName} as published`, function () {\n this.on('draft.document_id', '=', 'published.document_id')\n .andOn('draft.updated_at', '=', 'published.updated_at')\n .andOnNull('draft.published_at')\n .andOnNotNull('published.published_at');\n })\n .first()\n : await strapiDBConnection(tableName)\n .select('document_id')\n .from(`${tableName}`)\n .countDistinct('document_id as count')\n .groupBy('document_id')\n .first();\n countDocuments.published += Number(publishedDocuments?.count) || 0;\n\n const modifiedDocuments = await strapiDBConnection(tableName)\n .select('draft.document_id')\n .from(`${tableName} as draft`)\n .join(`${tableName} as published`, function () {\n this.on('draft.document_id', '=', 'published.document_id')\n .andOn('draft.updated_at', '!=', 'published.updated_at')\n .andOnNull('draft.published_at')\n .andOnNotNull('published.published_at');\n })\n .countDistinct('draft.document_id as count')\n .groupBy('draft.document_id')\n .first();\n countDocuments.modified += Number(modifiedDocuments?.count) || 0;\n }\n })\n );\n\n return countDocuments;\n },\n };\n};\n\nexport { createHomepageService };\n"],"names":["createHomepageService","strapi","MAX_DOCUMENTS","metadataService","plugin","service","permissionService","admin","services","permission","getConfiguration","contentTypeUids","coreStore","db","query","rawConfigurations","findMany","where","key","$in","map","contentType","rawConfiguration","JSON","parse","value","getPermittedContentTypes","readPermissions","role","users","id","requestContext","get","state","user","action","subject","filter","Boolean","getContentTypesMeta","allowedContentTypeUids","configurations","uid","configuration","find","config","fields","hasDraftAndPublish","contentTypes","push","settings","mainField","isLocalized","pluginOptions","i18n","localized","formatDocuments","documents","meta","populate","document","additionalFields","reduce","acc","documentId","locale","updatedAt","Date","title","publishedAt","contentTypeUid","contentTypeDisplayName","info","displayName","kind","permissionCheckerService","getPermissionChecker","create","userAbility","model","addStatusToDocuments","Promise","all","recentDocument","availableStatus","getMetadata","availableLocales","status","getStatus","undefined","queryLastDocuments","additionalQueryParams","draftAndPublishOnly","permittedContentTypes","contentTypesMeta","recentDocuments","permissionQuery","sanitizedQuery","read","limit","docs","flat","sort","a","b","valueOf","slice","getRecentlyPublishedDocuments","recentlyPublishedDocuments","getRecentlyUpdatedDocuments","recentlyUpdatedDocuments","getCountDocuments","countDocuments","draft","published","modified","strapiDBConnection","connection","tableName","collectionName","draftDocuments","whereNull","whereIn","select","from","groupBy","havingRaw","count","first","Number","publishedDocuments","countDistinct","join","on","andOn","andOnNull","andOnNotNull","modifiedDocuments"],"mappings":";;;;AAUA,MAAMA,qBAAwB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,WACtBK,MAAM,CAAC,eACPC,IAAI,CAAC,CAAC,EAAEN,SAAAA,CAAU,CAAC,CACnBa,CAAAA,aAAa,CAAC,sBACdN,CAAAA,CAAAA,OAAO,CAAC,aAAA,CAAA,CACRG,KAAK,EAAA;AACZhB,oBAAAA,cAAAA,CAAeE,SAAS,IAAIe,MAAOC,CAAAA,kBAAAA,EAAoBH,KAAU,CAAA,IAAA,CAAA;oBAEjE,MAAMU,iBAAAA,GAAoB,MAAMrB,kBAAmBE,CAAAA,SAAAA,CAAAA,CAChDK,MAAM,CAAC,mBAAA,CAAA,CACPC,IAAI,CAAC,CAAC,EAAEN,UAAU,SAAS,CAAC,EAC5Bc,IAAI,CAAC,CAAC,EAAEd,SAAAA,CAAU,aAAa,CAAC,EAAE,WAAA;AACjC,wBAAA,IAAI,CAACe,EAAE,CAAC,mBAAA,EAAqB,KAAK,uBAC/BC,CAAAA,CAAAA,KAAK,CAAC,kBAAA,EAAoB,MAAM,sBAChCC,CAAAA,CAAAA,SAAS,CAAC,oBAAA,CAAA,CACVC,YAAY,CAAC,wBAAA,CAAA;AAClB,qBAAA,CAAA,CACCL,aAAa,CAAC,4BAAA,CAAA,CACdN,OAAO,CAAC,qBACRG,KAAK,EAAA;AACRhB,oBAAAA,cAAAA,CAAeG,QAAQ,IAAIc,MAAOQ,CAAAA,iBAAAA,EAAmBV,KAAU,CAAA,IAAA,CAAA;AACjE;AACF,aAAA,CAAA,CAAA;YAGF,OAAOf,cAAAA;AACT;AACF,KAAA;AACF;;;;"}
|
|
@@ -156,6 +156,37 @@ const createHomepageService = ({ strapi })=>{
|
|
|
156
156
|
sort: 'updatedAt:desc'
|
|
157
157
|
});
|
|
158
158
|
return this.addStatusToDocuments(recentlyUpdatedDocuments);
|
|
159
|
+
},
|
|
160
|
+
async getCountDocuments () {
|
|
161
|
+
const permittedContentTypes = await getPermittedContentTypes();
|
|
162
|
+
// Fetch the configuration for each content type in a single query
|
|
163
|
+
const configurations = await getConfiguration(permittedContentTypes);
|
|
164
|
+
// Get the necessary metadata for the documents
|
|
165
|
+
const contentTypesMeta = getContentTypesMeta(permittedContentTypes, configurations);
|
|
166
|
+
const countDocuments = {
|
|
167
|
+
draft: 0,
|
|
168
|
+
published: 0,
|
|
169
|
+
modified: 0
|
|
170
|
+
};
|
|
171
|
+
await Promise.all(contentTypesMeta.map(async (meta)=>{
|
|
172
|
+
const strapiDBConnection = strapi.db.connection;
|
|
173
|
+
const tableName = strapi.contentType(meta.uid).collectionName;
|
|
174
|
+
if (tableName) {
|
|
175
|
+
const draftDocuments = await strapiDBConnection(tableName).whereNull('published_at').whereIn('document_id', function() {
|
|
176
|
+
this.select('document_id').from(tableName).groupBy('document_id').havingRaw('COUNT(*) = 1');
|
|
177
|
+
}).count('* as count').first();
|
|
178
|
+
countDocuments.draft += Number(draftDocuments?.count) || 0;
|
|
179
|
+
const publishedDocuments = meta.hasDraftAndPublish ? await strapiDBConnection(tableName).countDistinct('draft.document_id as count').from(`${tableName} as draft`).join(`${tableName} as published`, function() {
|
|
180
|
+
this.on('draft.document_id', '=', 'published.document_id').andOn('draft.updated_at', '=', 'published.updated_at').andOnNull('draft.published_at').andOnNotNull('published.published_at');
|
|
181
|
+
}).first() : await strapiDBConnection(tableName).select('document_id').from(`${tableName}`).countDistinct('document_id as count').groupBy('document_id').first();
|
|
182
|
+
countDocuments.published += Number(publishedDocuments?.count) || 0;
|
|
183
|
+
const modifiedDocuments = await strapiDBConnection(tableName).select('draft.document_id').from(`${tableName} as draft`).join(`${tableName} as published`, function() {
|
|
184
|
+
this.on('draft.document_id', '=', 'published.document_id').andOn('draft.updated_at', '!=', 'published.updated_at').andOnNull('draft.published_at').andOnNotNull('published.published_at');
|
|
185
|
+
}).countDistinct('draft.document_id as count').groupBy('draft.document_id').first();
|
|
186
|
+
countDocuments.modified += Number(modifiedDocuments?.count) || 0;
|
|
187
|
+
}
|
|
188
|
+
}));
|
|
189
|
+
return countDocuments;
|
|
159
190
|
}
|
|
160
191
|
};
|
|
161
192
|
};
|