-
Notifications
You must be signed in to change notification settings - Fork 3
/
helper.js
106 lines (95 loc) · 3.61 KB
/
helper.js
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
const sanitizerConfig = {
// FORBID_TAGS: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr'],
ALLOWED_TAGS: ['b', 'i', 'u', 'a', 'br', 'p', 'code', 'span', 'pre'],
FORBID_ATTR: ['style'],
IN_PLACE: true
}
angular
.module('app')
.factory('Base64Encoder', function () {
return {
encode: (value) => btoa(unescape(encodeURIComponent(value))),
decode: (value) => decodeURIComponent(escape(atob(value))),
}
})
.factory('HtmlSanitizer', function () {
return {
sanitize: (value) => DOMPurify.sanitize(value, sanitizerConfig)
}
})
.factory('PromiseCacheService', function ($q, $log, $localStorage, TimeIntervalService) {
$log.debug('$localStorage:', $localStorage)
const defaultCacheTimeInterval = '10min';
const internalCacheKey = 'blogit';
if (!$localStorage[internalCacheKey]) {
$localStorage[internalCacheKey] = {};
}
let internalStorage = $localStorage[internalCacheKey];
function softClone(data) {
if (Array.isArray(data)) {
return data.map(item => softClone(item))
}
return Object.assign({}, data)
}
return {
getOrSet: async (cacheKey, promiseInFunction, time = defaultCacheTimeInterval) => {
const timeInterval = TimeIntervalService.createFromString(time)
let cacheItem = internalStorage[cacheKey];
if (cacheItem && cacheItem.expiresAt > (new Date()).getTime()) {
$log.debug(
'Cache hit detected by key',
`"${cacheKey}"`,
'with value',
cacheItem.value,
'expires at',
new Date(cacheItem.expiresAt)
)
const cacheItemValue = softClone(cacheItem.value)
return $q.resolve(
Array.isArray(cacheItemValue)
? cacheItemValue
: Object.assign({}, cacheItemValue)
)
}
$log.debug('No cache hit detected', cacheKey)
const promise = promiseInFunction();
internalStorage[cacheKey] = {
value: softClone(await promise),
expiresAt: timeInterval.getTotalTime()
}
return promise
}
}
})
.factory('TimeIntervalService', function () {
return {
createFromString: (string) => {
const parts = String(string).split(' ')
const minutes = parseInt(parts.find(part => part.includes('min'))) || 0
const hours = parseInt(parts.find(part => part.includes('hour'))) || 0
return {
minutes: minutes,
hours: hours,
toSeconds: () => minutes * 60 + hours * 3600,
toMilliSeconds: function () {
return this.toSeconds() * 1000
},
getTotalTime: function () {
return (new Date((new Date()).getTime() + this.toMilliSeconds())).getTime()
},
}
}
}
})
;
Array.prototype.includesArray = function (array) {
if (array.length > this.length) {
return false
}
for (const index in array) {
if (array.hasOwnProperty(index) && !this.includes(array[index])) {
return false
}
}
return true
}