@vegan-friendly/strapi-plugin-elasticsearch 0.0.11-alpha.5 → 0.0.11-alpha.7

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.
Files changed (51) hide show
  1. package/.vscode/settings.json +3 -0
  2. package/README.md +0 -4
  3. package/admin/src/components/Initializer/index.js +26 -0
  4. package/admin/src/components/PluginIcon/index.js +12 -0
  5. package/admin/src/components/SubNavigation/index.js +48 -0
  6. package/admin/src/index.js +63 -0
  7. package/admin/src/pages/App/index.js +29 -0
  8. package/admin/src/pages/ConfigureCollection/index.js +225 -0
  9. package/admin/src/pages/ConfigureCollectionList/index.js +266 -0
  10. package/admin/src/pages/Homepage/index.js +168 -0
  11. package/admin/src/pages/ViewIndexingRunLog/index.js +124 -0
  12. package/admin/src/pluginId.js +5 -0
  13. package/admin/src/translations/en.json +1 -0
  14. package/admin/src/translations/fr.json +1 -0
  15. package/admin/src/utils/apiUrls.js +14 -0
  16. package/admin/src/utils/axiosInstance.js +40 -0
  17. package/admin/src/utils/getTrad.js +5 -0
  18. package/package.json +40 -80
  19. package/server/bootstrap.js +142 -0
  20. package/server/config/index.js +6 -0
  21. package/server/content-types/index.js +9 -0
  22. package/server/content-types/indexing-logs.js +35 -0
  23. package/server/content-types/name-prefix.js +0 -0
  24. package/server/content-types/tasks.js +52 -0
  25. package/server/controllers/configure-indexing.js +66 -0
  26. package/server/controllers/index.js +15 -0
  27. package/server/controllers/log-indexing.js +11 -0
  28. package/server/controllers/perform-indexing.js +28 -0
  29. package/server/controllers/perform-search.js +31 -0
  30. package/server/controllers/setup-info.js +14 -0
  31. package/server/destroy.js +5 -0
  32. package/server/index.js +25 -0
  33. package/server/middlewares/index.js +3 -0
  34. package/server/policies/index.js +3 -0
  35. package/server/register.js +5 -0
  36. package/server/routes/configure-indexing.js +42 -0
  37. package/server/routes/index.js +13 -0
  38. package/server/routes/perform-indexing.js +24 -0
  39. package/server/routes/perform-search.js +14 -0
  40. package/server/routes/run-log.js +12 -0
  41. package/server/routes/setup-info.js +12 -0
  42. package/server/services/configure-indexing.js +184 -0
  43. package/server/services/es-interface.js +187 -0
  44. package/server/services/helper.js +305 -0
  45. package/server/services/index.js +19 -0
  46. package/server/services/log-indexing.js +26 -0
  47. package/server/services/perform-indexing.js +173 -0
  48. package/server/services/schedule-indexing.js +65 -0
  49. package/server/services/transform-content.js +22 -0
  50. package/strapi-admin.js +3 -0
  51. package/strapi-server.js +3 -0
@@ -0,0 +1,187 @@
1
+ const { Client } = require('@elastic/elasticsearch')
2
+ const fs = require('fs')
3
+ const path = require('path');
4
+
5
+
6
+
7
+ let client = null;
8
+
9
+ module.exports = ({ strapi }) => ({
10
+ async initializeSearchEngine({host, uname, password, cert}){
11
+ try
12
+ {
13
+ client = new Client({
14
+ node: host,
15
+ auth: {
16
+ username: uname,
17
+ password: password
18
+ },
19
+ tls: {
20
+ ca: cert,
21
+ rejectUnauthorized: false
22
+ }
23
+ });
24
+ }
25
+ catch (err)
26
+ {
27
+ if (err.message.includes('ECONNREFUSED'))
28
+ {
29
+ console.error('strapi-plugin-elasticsearch : Connection to ElasticSearch at ', host, ' refused.')
30
+ console.error(err);
31
+ }
32
+ else
33
+ {
34
+ console.error('strapi-plugin-elasticsearch : Error while initializing connection to ElasticSearch.')
35
+ console.error(err);
36
+ }
37
+ throw(err);
38
+ }
39
+ },
40
+ async createIndex(indexName){
41
+ try{
42
+ const exists = await client.indices.exists({index: indexName});
43
+ if (!exists)
44
+ {
45
+ console.log('strapi-plugin-elasticsearch : Search index ', indexName, ' does not exist. Creating index.');
46
+
47
+ await client.indices.create({
48
+ index: indexName,
49
+ });
50
+ }
51
+ }
52
+ catch (err)
53
+ {
54
+ if (err.message.includes('ECONNREFUSED'))
55
+ {
56
+ console.log('strapi-plugin-elasticsearch : Error while creating index - connection to ElasticSearch refused.')
57
+ console.log(err);
58
+ }
59
+ else
60
+ {
61
+ console.log('strapi-plugin-elasticsearch : Error while creating index.')
62
+ console.log(err);
63
+ }
64
+ }
65
+ },
66
+ async deleteIndex(indexName){
67
+ try{
68
+ await client.indices.delete({
69
+ index: indexName
70
+ });
71
+ }
72
+ catch(err)
73
+ {
74
+ if (err.message.includes('ECONNREFUSED'))
75
+ {
76
+ console.log('strapi-plugin-elasticsearch : Connection to ElasticSearch refused.')
77
+ console.log(err);
78
+ }
79
+ else
80
+ {
81
+ console.log('strapi-plugin-elasticsearch : Error while deleting index to ElasticSearch.')
82
+ console.log(err);
83
+ }
84
+ }
85
+ },
86
+ async attachAliasToIndex(indexName) {
87
+ try{
88
+ const pluginConfig = await strapi.config.get('plugin.elasticsearch');
89
+ const aliasName = pluginConfig.indexAliasName;
90
+ const aliasExists = await client.indices.existsAlias({name: aliasName});
91
+ if (aliasExists)
92
+ {
93
+ console.log('strapi-plugin-elasticsearch : Alias with this name already exists, removing it.');
94
+ await client.indices.deleteAlias({index: '*', name: aliasName});
95
+ }
96
+ const indexExists = await client.indices.exists({index: indexName});
97
+ if (!indexExists)
98
+ await this.createIndex(indexName);
99
+ console.log('strapi-plugin-elasticsearch : Attaching the alias ', aliasName, ' to index : ', indexName);
100
+ await client.indices.putAlias({index: indexName, name: aliasName})
101
+ }
102
+ catch(err)
103
+ {
104
+ if (err.message.includes('ECONNREFUSED'))
105
+ {
106
+ console.log('strapi-plugin-elasticsearch : Attaching alias to the index - Connection to ElasticSearch refused.')
107
+ console.log(err);
108
+ }
109
+ else
110
+ {
111
+ console.log('strapi-plugin-elasticsearch : Attaching alias to the index - Error while setting up alias within ElasticSearch.')
112
+ console.log(err);
113
+ }
114
+ }
115
+ },
116
+ async checkESConnection() {
117
+ if (!client)
118
+ return false;
119
+ try {
120
+ await client.ping();
121
+ return true;
122
+ }
123
+ catch(error)
124
+ {
125
+ console.error('strapi-plugin-elasticsearch : Could not connect to Elastic search.')
126
+ console.error(error);
127
+ return false;
128
+ }
129
+
130
+ },
131
+ async indexDataToSpecificIndex({itemId, itemData}, iName){
132
+ try
133
+ {
134
+ await client.index({
135
+ index: iName,
136
+ id: itemId,
137
+ document: itemData
138
+ })
139
+ await client.indices.refresh({ index: iName });
140
+ }
141
+ catch(err){
142
+ console.log('strapi-plugin-elasticsearch : Error encountered while indexing data to ElasticSearch.')
143
+ console.log(err);
144
+ throw err;
145
+ }
146
+ },
147
+ async indexData({itemId, itemData}) {
148
+ const pluginConfig = await strapi.config.get('plugin.elasticsearch');
149
+ return await this.indexDataToSpecificIndex({itemId, itemData}, pluginConfig.indexAliasName);
150
+ },
151
+ async removeItemFromIndex({itemId}) {
152
+ const pluginConfig = await strapi.config.get('plugin.elasticsearch');
153
+ try
154
+ {
155
+ await client.delete({
156
+ index: pluginConfig.indexAliasName,
157
+ id: itemId
158
+ });
159
+ await client.indices.refresh({ index: pluginConfig.indexAliasName });
160
+ }
161
+ catch(err){
162
+ if (err.meta.statusCode === 404)
163
+ console.error('strapi-plugin-elasticsearch : The entry to be removed from the index already does not exist.')
164
+ else
165
+ {
166
+ console.error('strapi-plugin-elasticsearch : Error encountered while removing indexed data from ElasticSearch.')
167
+ throw err;
168
+ }
169
+ }
170
+ },
171
+ async searchData(searchQuery){
172
+ try
173
+ {
174
+ const pluginConfig = await strapi.config.get('plugin.elasticsearch');
175
+ const result= await client.search({
176
+ index: pluginConfig.indexAliasName,
177
+ ...searchQuery
178
+ });
179
+ return result;
180
+ }
181
+ catch(err)
182
+ {
183
+ console.log('Search : elasticClient.searchData : Error encountered while making a search request to ElasticSearch.')
184
+ throw err;
185
+ }
186
+ }
187
+ });
@@ -0,0 +1,305 @@
1
+
2
+ ///START : via https://raw.githubusercontent.com/Barelydead/strapi-plugin-populate-deep/main/server/helpers/index.js
3
+
4
+ const { isEmpty, merge } = require("lodash/fp");
5
+ const transformServiceProvider = require('./transform-content');
6
+
7
+ const getPluginStore = () => {
8
+ return strapi.store({
9
+ environment: '',
10
+ type: 'plugin',
11
+ name: 'elasticsearch',
12
+ });
13
+ }
14
+
15
+
16
+ const getModelPopulationAttributes = (model) => {
17
+ if (model.uid === "plugin::upload.file") {
18
+ const { related, ...attributes } = model.attributes;
19
+ return attributes;
20
+ }
21
+
22
+ return model.attributes;
23
+ };
24
+
25
+ const getFullPopulateObject = (modelUid, maxDepth = 20, ignore) => {
26
+ const skipCreatorFields = true;
27
+
28
+ if (maxDepth <= 1) {
29
+ return true;
30
+ }
31
+ if (modelUid === "admin::user" && skipCreatorFields) {
32
+ return undefined;
33
+ }
34
+
35
+ const populate = {};
36
+ const model = strapi.getModel(modelUid);
37
+ if (ignore && !ignore.includes(model.collectionName)) ignore.push(model.collectionName)
38
+ for (const [key, value] of Object.entries(
39
+ getModelPopulationAttributes(model)
40
+ )) {
41
+ if (ignore?.includes(key)) continue
42
+ if (value) {
43
+ if (value.type === "component") {
44
+ populate[key] = getFullPopulateObject(value.component, maxDepth - 1);
45
+ } else if (value.type === "dynamiczone") {
46
+ const dynamicPopulate = value.components.reduce((prev, cur) => {
47
+ const curPopulate = getFullPopulateObject(cur, maxDepth - 1);
48
+ return curPopulate === true ? prev : merge(prev, curPopulate);
49
+ }, {});
50
+ populate[key] = isEmpty(dynamicPopulate) ? true : dynamicPopulate;
51
+ } else if (value.type === "relation") {
52
+ const relationPopulate = getFullPopulateObject(
53
+ value.target,
54
+ (key === 'localizations') && maxDepth > 2 ? 1 : maxDepth - 1,
55
+ ignore
56
+ );
57
+ if (relationPopulate) {
58
+ populate[key] = relationPopulate;
59
+ }
60
+ } else if (value.type === "media") {
61
+ populate[key] = true;
62
+ }
63
+ }
64
+ }
65
+ return isEmpty(populate) ? true : { populate };
66
+ };
67
+
68
+ ///END : via https://raw.githubusercontent.com/Barelydead/strapi-plugin-populate-deep/main/server/helpers/index.js
69
+
70
+
71
+ /*
72
+ //Example config to cover extraction cases
73
+ collectionConfig[collectionName] = {
74
+ 'major' : {index: true},
75
+ 'sections' : { index: true, searchFieldName: 'information',
76
+ 'subfields' : [
77
+ { 'component' : 'try.paragraph',
78
+ 'field' : 'Text'},
79
+ { 'component' : 'try.paragraph',
80
+ 'field' : 'Heading'},
81
+ { 'component' : 'try.footer',
82
+ 'field' : 'footer_link',
83
+ 'subfields' :[ {
84
+ 'component' : 'try.link',
85
+ 'field' : 'display_text'
86
+ }]
87
+ }] },
88
+ 'seo_details' : {
89
+ index: true, searchFieldName: 'seo',
90
+ 'subfields' : [
91
+ {
92
+ 'component' : 'try.seo',
93
+ 'field' : 'meta_description'
94
+ }
95
+ ]
96
+ },
97
+ 'changelog' : {
98
+ index: true, searchFieldName: 'breakdown',
99
+ 'subfields' : [
100
+ {
101
+ 'component' : 'try.revision',
102
+ 'field' : 'summary'
103
+ }
104
+ ]
105
+ }
106
+ }
107
+ */
108
+ function extractSubfieldData({config, data }) {
109
+ let returnData = '';
110
+ if (Array.isArray(data))
111
+ {
112
+ const dynDataItems = data;
113
+ for (let r=0; r< dynDataItems.length; r++)
114
+ {
115
+ const extractItem = dynDataItems[r];
116
+ for (let s=0; s<config.length; s++)
117
+ {
118
+ const conf = config[s];
119
+ if (Object.keys(extractItem).includes('__component'))
120
+ {
121
+ if (conf.component === extractItem.__component &&
122
+ !Object.keys(conf).includes('subfields') &&
123
+ typeof extractItem[conf['field']] !== "undefined" &&
124
+ extractItem[conf['field']])
125
+ {
126
+ let val = extractItem[conf['field']]
127
+ if (Object.keys(conf).includes('transform')
128
+ && conf['transform'] === 'markdown')
129
+ val = transformServiceProvider.transform({content: val, from: 'markdown'});
130
+ returnData = returnData + '\n' + val;
131
+ }
132
+ else if (conf.component === extractItem.__component &&
133
+ Object.keys(conf).includes('subfields'))
134
+ {
135
+ returnData = returnData + '\n' + extractSubfieldData({
136
+ config: conf['subfields'], data: extractItem[conf['field']]});
137
+ }
138
+ }
139
+ else
140
+ {
141
+ if (!Object.keys(conf).includes('subfields') &&
142
+ typeof extractItem[conf['field']] !== "undefined" &&
143
+ extractItem[conf['field']])
144
+ {
145
+ let val = extractItem[conf['field']]
146
+ if (Object.keys(conf).includes('transform')
147
+ && conf['transform'] === 'markdown')
148
+ val = transformServiceProvider.transform({content: val, from: 'markdown'});
149
+ returnData = returnData + '\n' + val;
150
+ }
151
+ else if (Object.keys(conf).includes('subfields'))
152
+ {
153
+ returnData = returnData + '\n' + extractSubfieldData({
154
+ config: conf['subfields'], data: extractItem[conf['field']]});
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+ else //for single component as a field
161
+ {
162
+ for (let s=0; s<config.length; s++)
163
+ {
164
+ const conf = config[s];
165
+ if (!Object.keys(conf).includes('subfields') &&
166
+ typeof data[conf['field']] !== "undefined" &&
167
+ data[conf['field']])
168
+ returnData = returnData + '\n' + data[conf['field']]
169
+ else if (Object.keys(conf).includes('subfields'))
170
+ {
171
+ returnData = returnData + '\n' + extractSubfieldData({
172
+ config: conf['subfields'], data: data[conf['field']]});
173
+ }
174
+ }
175
+ }
176
+ return returnData;
177
+ }
178
+
179
+ module.exports = ({ strapi }) => ({
180
+ async getElasticsearchInfo() {
181
+ const configureService = strapi.plugins['elasticsearch'].services.configureIndexing;
182
+ const esInterface = strapi.plugins['elasticsearch'].services.esInterface;
183
+ const pluginConfig = await strapi.config.get('plugin.elasticsearch');
184
+
185
+ const connected = pluginConfig.searchConnector && pluginConfig.searchConnector.host
186
+ ? await esInterface.checkESConnection() : false;
187
+
188
+ return {
189
+ indexingCronSchedule : pluginConfig.indexingCronSchedule || "Not configured",
190
+ elasticHost : pluginConfig.searchConnector ?
191
+ pluginConfig.searchConnector.host || "Not configured" : "Not configured",
192
+ elasticUserName : pluginConfig.searchConnector ?
193
+ pluginConfig.searchConnector.username || "Not configured" : "Not configured",
194
+ elasticCertificate : pluginConfig.searchConnector ?
195
+ pluginConfig.searchConnector.certificate || "Not configured" : "Not configured",
196
+ elasticIndexAlias : pluginConfig.indexAliasName || "Not configured",
197
+ connected : connected,
198
+ initialized : configureService.isInitialized()
199
+ }
200
+ },
201
+ isCollectionDraftPublish({collectionName}) {
202
+ const model = strapi.getModel(collectionName);
203
+ return model.attributes.publishedAt ? true : false
204
+ },
205
+ getPopulateAttribute({collectionName}) {
206
+ //TODO : We currently have set populate to upto 4 levels, should
207
+ //this be configurable or a different default value?
208
+ return getFullPopulateObject(collectionName, 4, []);
209
+ },
210
+ getIndexItemId ({collectionName, itemId}) {
211
+ return collectionName+'::' + itemId;
212
+ },
213
+ async getCurrentIndexName () {
214
+ const pluginStore = getPluginStore();
215
+ const settings = await pluginStore.get({ key: 'configsettings' });
216
+ let indexName = 'strapi-plugin-elasticsearch-index_000001';
217
+ if (settings)
218
+ {
219
+ const objSettings = JSON.parse(settings);
220
+ if (Object.keys(objSettings).includes('indexConfig'))
221
+ {
222
+ const idxConfig = objSettings['indexConfig'];
223
+ indexName = idxConfig['name'];
224
+ }
225
+ }
226
+ return indexName;
227
+ },
228
+ async getIncrementedIndexName () {
229
+ const currentIndexName = await this.getCurrentIndexName();
230
+ const number = parseInt(currentIndexName.split('index_')[1]);
231
+ return 'strapi-plugin-elasticsearch-index_' + String(number+1).padStart(6,'0');
232
+ },
233
+ async storeCurrentIndexName (indexName) {
234
+ const pluginStore = getPluginStore();
235
+ const settings = await pluginStore.get({ key: 'configsettings' });
236
+ if (settings)
237
+ {
238
+ const objSettings = JSON.parse(settings);
239
+ objSettings['indexConfig'] = {'name' : indexName};
240
+ await pluginStore.set({ key: 'configsettings', value : JSON.stringify(objSettings)});
241
+ }
242
+ else
243
+ {
244
+ const newSettings = JSON.stringify({'indexConfig' : {'name' : indexName}})
245
+ await pluginStore.set({ key: 'configsettings', value : newSettings});
246
+ }
247
+ },
248
+ modifySubfieldsConfigForExtractor(collectionConfig) {
249
+ const collectionName = Object.keys(collectionConfig)[0];
250
+ const attributes = Object.keys(collectionConfig[collectionName]);
251
+ for (let r=0; r< attributes.length; r++)
252
+ {
253
+ const attr = attributes[r];
254
+ const attribFields = Object.keys(collectionConfig[collectionName][attr]);
255
+ if (attribFields.includes('subfields'))
256
+ {
257
+ const subfielddata = collectionConfig[collectionName][attr]['subfields'];
258
+ if (subfielddata.length > 0)
259
+ {
260
+ try {
261
+ const subfieldjson = JSON.parse(subfielddata)
262
+ if (Object.keys(subfieldjson).includes('subfields'))
263
+ collectionConfig[collectionName][attr]['subfields'] = subfieldjson['subfields']
264
+ }
265
+ catch(err)
266
+ {
267
+ continue;
268
+ }
269
+ }
270
+ }
271
+ }
272
+ return collectionConfig;
273
+ },
274
+ extractDataToIndex({collectionName, data, collectionConfig}) {
275
+ collectionConfig = this.modifySubfieldsConfigForExtractor(collectionConfig);
276
+ const fti = Object.keys(collectionConfig[collectionName]);
277
+ const document = {}
278
+ for (let k = 0; k < fti.length; k++)
279
+ {
280
+ const fieldConfig = collectionConfig[collectionName][fti[k]];
281
+ if (fieldConfig.index)
282
+ {
283
+ let val = null;
284
+ if (Object.keys(fieldConfig).includes('subfields'))
285
+ {
286
+ val = extractSubfieldData({config: fieldConfig['subfields'], data: data[fti[k]]})
287
+ val = val ? val.trim() : val
288
+ }
289
+ else
290
+ {
291
+ val = data[fti[k]];
292
+ if (Object.keys(fieldConfig).includes('transform') &&
293
+ fieldConfig['transform'] === 'markdown')
294
+ val = transformServiceProvider.transform({content: val, from: 'markdown'});
295
+ }
296
+
297
+ if (Object.keys(fieldConfig).includes('searchFieldName'))
298
+ document[fieldConfig['searchFieldName']] = val;
299
+ else
300
+ document[fti[k]] = val;
301
+ }
302
+ }
303
+ return document;
304
+ }
305
+ });
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ const configureIndexing = require('./configure-indexing');
4
+ const scheduleIndexing = require('./schedule-indexing');
5
+ const esInterface = require('./es-interface');
6
+ const indexer = require('./perform-indexing');
7
+ const logIndexing = require('./log-indexing');
8
+ const helper = require('./helper');
9
+ const transformContent = require('./transform-content');
10
+
11
+ module.exports = {
12
+ configureIndexing,
13
+ scheduleIndexing,
14
+ esInterface,
15
+ indexer,
16
+ logIndexing,
17
+ helper,
18
+ transformContent
19
+ };
@@ -0,0 +1,26 @@
1
+ module.exports = ({ strapi }) => ({
2
+ async recordIndexingPass(message) {
3
+ const entry = await strapi.entityService.create('plugin::elasticsearch.indexing-log', {
4
+ data : {
5
+ status: 'pass',
6
+ details: message
7
+ }
8
+ });
9
+ },
10
+ async recordIndexingFail(message) {
11
+ const entry = await strapi.entityService.create('plugin::elasticsearch.indexing-log', {
12
+ data : {
13
+ status: 'fail',
14
+ details: String(message)
15
+ }
16
+ });
17
+ },
18
+ async fetchIndexingLogs(count = 50) {
19
+ const records = await strapi.entityService.findMany('plugin::elasticsearch.indexing-log', {
20
+ sort: { createdAt: 'DESC' },
21
+ start: 0,
22
+ limit: count
23
+ });
24
+ return records;
25
+ }
26
+ });