-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersistance.js
More file actions
260 lines (208 loc) · 6.9 KB
/
Copy pathpersistance.js
File metadata and controls
260 lines (208 loc) · 6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
const path = require('path')
const admin = require('firebase-admin');
const uniqBy = require('lodash.uniqby')
let serviceAccount = require(path.join(__dirname, './google-credentials-heroku.json'))
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });
let db = admin.firestore()
function sanitize(inputString) {
return inputString.trim().toLowerCase()
}
function addKeyLearning({
createdBy = '',
keyLearning = '',
guidingContext = '',
clientMap = {},
industryMap = {},
clientTags = [],
industryTags = [],
relatedThemes = [] }) {
return db
.collection('keyLearnings')
.doc()
.set({
keyLearning,
guidingContext,
clientTags,
clientMap,
industryMap,
industryTags,
relatedThemes,
createdBy,
createdAt: new Date()
})
}
function addTag({ tag }, type) {
const validTypes = ['client', 'industry', 'theme']
if (!validTypes.includes(type)) {
throw new Error('Tag type is invalid. Use one of: ', validTypes.join(' '))
}
const COLLECTIONS_MAP = { client: 'clientTags', industry: 'industryTags', theme: 'themeTags' }
return db
.collection(COLLECTIONS_MAP[type])
.doc()
.set({ tag })
}
function dedupeById(results) {
// TODO: use the `id` attribute to dedupe this list, and return it.
return results
}
function tryQuery(query, outputArray, nextQueries = []) {
const rest = nextQueries.map(q => q.get)
const promises = [query.get, ...rest]
return Promise.all(promises).then(querySnapshots => {
const results = []
querySnapshots.forEach(querySnapshot => {
if (querySnapshot && querySnapshot.length) {
console.log(querySnapshot)
querySnapshot.forEach(doc => {
results.push(doc.data())
})
}
})
return results
}).catch(e => {
console.log('🚩Query failed ', e)
})
}
async function getAll() {
const snapshot = await db.collection('keyLearnings').get()
return snapshot.docs.map(doc => doc.data());
}
function searchForKeyLearning({ industryTags = [], clientTags = [], themeTags = [], cursor = 0, limit = 3 }) {
console.log(
'🔎\nSearching for key learning with themeTags: ',
themeTags,
'\nclient tags: ',
clientTags,
'\nindustryTags: ',
industryTags
)
const results = [
/* 1. everything that matches all present criteria */
/* 2. everything that matches theme and industry criteria */
/* 3. everything that matches theme and client criteria */
/* 4. everything that matches theme criteria only */
]
/*
clientTags and themeTags actually only ever contain 1 value. So let's destructure that
*/
let [industryTag] = industryTags
if (industryTag) { industryTag = sanitize(industryTag) }
let [clientTag] = clientTags
if (clientTag) { clientTag = sanitize(clientTag) }
const keyLearningsRef = db.collection('keyLearnings')
const sanitizedThemeTags = themeTags.map(tag => sanitize(tag))
console.log(`
\n
theme tags, sanitized:
${sanitizedThemeTags}
\n
`)
let queryRef = keyLearningsRef.where('relatedThemes', 'array-contains-any', sanitizedThemeTags)
let hasClientTags = clientTags.length > 0
let hasIndustryTags = industryTags.length > 0
if (hasClientTags) {
//console.log(' -> has client tags ', clientTag)
//queryRef = queryRef.where(`clientMap.${clientTag}`, '==', true)
}
if (hasIndustryTags) {
//console.log(' -> has industry tags ', industryTag)
//queryRef = queryRef.where(`industryMap.${industryTag}`, '==', true)
}
const promises = []
promises.push(queryRef.get().then(
querySnapshot => {
if (querySnapshot.empty) {
console.log('No matching documents for key . 😞');
}
querySnapshot.forEach(doc => {
results.push(Object.assign({}, doc.data(), {id: doc.id}))
})
return results
}
).catch(e => {
console.log('-----> failed at get: ', e)
}))
if (hasIndustryTags) {
promises.push(keyLearningsRef.where(`industryMap.${industryTag}`, '==', true).get().then(
querySnapshot => {
if (querySnapshot.empty) {
console.log('No matching documents for industry map 😞');
}
querySnapshot.forEach(doc => {
results.push(Object.assign({}, doc.data(), {id: doc.id}))
})
return results
}
))
}
if (hasClientTags) {
promises.push(keyLearningsRef.where(`clientMap.${clientTag}`, '==', true).get().then(
querySnapshot => {
if (querySnapshot.empty) {
console.log('No matching documents for client map 😞');
}
querySnapshot.forEach(doc => {
results.push(Object.assign({}, doc.data(), {id: doc.id}))
})
return results
}
))
}
return Promise.all(promises).then(([ themes, industry, client ]) => {
let res = [...themes]
if (industry) {
res = [...res, ...industry]
// [Any theme matched, industry matched, client matched]
// How many results matched ALL themes
// How many results matched SOME themes
// How many results matched industry
// How many results matched client
}
if (client) {
res = [...res, ...client]
}
console.log('\nid ', res.map(({id}) => id), '\n')
console.log('\n length w/o uniq ', res.length, ' \n length w uniq ', uniqBy(res, 'id').length, ' cursor: ', cursor, 'limit ', limit)
const results = uniqBy(res, 'id')
// const results = res
return {
results: results.filter((_, index) => (index >= cursor && index < (cursor + limit))),
total: results.length
}
}).catch(e => {
console.log('-> Promise all failed at #searchForKeyLearnings ', e)
})
// let relatedThemeClientQuery = relatedThemeQuery.where('clientTags', 'array-contains-any', clientTags.map(tag => sanitize(tag)))
// let relatedThemeIndustryQuery = relatedThemeQuery.where('industryTags', 'array-contains-any', industryTags.map(tag => sanitize(tag)))
// let compoundQuery = relatedThemeIndustryQuery.where('clientTags', 'array-contains-any', clientTags.map(tag => sanitize(tag)))
// let nextQueriesArray = []
// if (hasIndustryTags) {
// nextQueriesArray.push(relatedThemeIndustryQuery)
// }
// if (hasClientTags) {
// nextQueriesArray.push(relatedThemeClientQuery)
// }
// nextQueriesArray.push(relatedThemeQuery)
// 1. perform the query with all criteria
// return tryQuery(compoundQuery, results, nextQueriesArray)
// TODO: if the query didn't return any result, change the language to say: "We found no results for all your criteria. These results meet some of your criteria:"
}
function getClientTags() {
return db.collection('clientTags').get()
}
function getIndustryTags() {
return db.collection('industryTags').get()
}
function getThemeTags() {
return db.collection('themeTags').get()
}
module.exports = {
addKeyLearning,
searchForKeyLearning,
getClientTags,
getIndustryTags,
getThemeTags,
addTag,
sanitize
}