-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathutils.ts
More file actions
322 lines (271 loc) Β· 7.29 KB
/
utils.ts
File metadata and controls
322 lines (271 loc) Β· 7.29 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import { startOfISOWeek, endOfISOWeek } from 'date-fns';
import { zonedTimeToUtc } from 'date-fns-tz';
import { snakeCase } from 'lodash';
import { isNullOrUndefined } from './object';
import { remoteConfig } from '../remoteConfig';
import { ChangeObject } from '../types';
import { logger } from '../logger';
import slugify from 'slugify';
const REMOVE_SPECIAL_CHARACTERS_REGEX = /[^a-zA-Z0-9-_#.]/g;
export const DELETED_BY_WORKER = 'worker';
export const playwrightUser = {
id: '8bf2UpTsHFnczzOlk0mtg',
};
export const ghostUser = {
id: '404',
username: 'ghost',
name: 'Deleted user',
image:
'https://media.daily.dev/image/upload/s--hNIUzLiO--/f_auto/v1705327420/public/ghost_vlftth',
};
export const deletedPost = {
id: '404',
};
export const systemUser = {
id: 'system',
username: 'system',
name: 'System',
};
export const demoCompany = {
id: 'e8c7a930-ca69-4cba-b26c-b6c810d6ab7d',
};
interface GetTimezonedIsoWeekProps {
date: Date;
timezone: string;
}
export const getTimezonedStartOfISOWeek = ({
date,
timezone,
}: GetTimezonedIsoWeekProps): Date => {
return zonedTimeToUtc(startOfISOWeek(date), timezone);
};
export const getTimezonedEndOfISOWeek = ({
date,
timezone,
}: GetTimezonedIsoWeekProps): Date => {
return zonedTimeToUtc(endOfISOWeek(date), timezone);
};
export const updateFlagsStatement = <Entity extends { flags: object }>(
update: Partial<Entity['flags']>,
): (() => string) => {
return () => `flags || '${JSON.stringify(update)}'`;
};
export const updateNotificationFlags = <
Entity extends {
notificationFlags: object;
},
>(
update: Partial<Entity['notificationFlags']>,
): (() => string) => {
return () => `notificationFlags || '${JSON.stringify(update)}'`;
};
export const updateSubscriptionFlags = <
Entity extends {
subscriptionFlags: object;
},
>(
update: Partial<Entity['subscriptionFlags']>,
): (() => string) => {
return () => `subscriptionFlags || '${JSON.stringify(update)}'`;
};
/**
* Remove special characters from a string
* Only allows alphanumeric, -, _, # and . characters
*
* @param text
*/
export const removeSpecialCharacters = (text: string): string => {
return text.replace(REMOVE_SPECIAL_CHARACTERS_REGEX, '');
};
/**
* Remove duplicate values from an array
*
* @param array
*/
export const uniqueifyArray = <T>(array: T[]): T[] => {
return [...new Set(array)];
};
/**
* Remove duplicate values from an array of objects per unique key
*
* @template T
* @template R
* @param {T[]} array Array of objects
* @param {(item: T) => string} uniqueKey Function to get the unique key from the item
* @param {(item: T, index: number, uniqueKey: string) => R} [processItem] Optional function to process the item before adding it to the result array
* @return {*} {R[]}
*/
export const uniqueifyObjectArray = <T, R = T>(
array: T[],
uniqueKey: (item: T) => string,
processItem?: (item: T, index: number, uniqueKey: string) => R,
): R[] => {
const uniqueMap = array.reduce((acc, item, index) => {
const itemKey = uniqueKey(item);
if (!acc.has(itemKey)) {
const newItem =
typeof processItem === 'function'
? processItem(item, index, itemKey)
: item;
acc.set(itemKey, newItem as unknown as R);
}
return acc;
}, new Map<string, R>());
return Array.from(uniqueMap.values());
};
/**
* Remove empty values from an array
*
* @param array
*/
export const removeEmptyValues = <T>(array: T[]): T[] => array.filter(Boolean);
/**
* Check if the current environment is production
*
* @returns boolean
*/
export const isProd = process.env.NODE_ENV === 'production';
export const isTest = process.env.NODE_ENV === 'test';
export const parseDate = (
date: string | Date | undefined,
): Date | undefined => {
if (!date) {
return undefined;
}
const parsedDate = new Date(date);
if (Number.isNaN(parsedDate.getTime())) {
return undefined;
}
if (parsedDate.getTime() < 0) {
return undefined;
}
return parsedDate;
};
export const toGQLEnum = (value: Record<string, string>, name: string) => {
return `enum ${name} { ${Object.values(value).join(' ')} }`;
};
export const toChangeObject = <T>(entity: T): ChangeObject<T> =>
JSON.parse(Buffer.from(JSON.stringify(entity)).toString('utf-8').trim());
export function camelCaseToSnakeCase(
obj: Record<string, unknown>,
): Record<string, unknown> {
const snakeObj: Record<string, unknown> = {};
for (const key in obj) {
snakeObj[snakeCase(key)] = obj[key];
}
return snakeObj;
}
export function debeziumTimeToDate(time: number): Date {
return new Date(Math.floor(time / 1000));
}
export const getDateBaseFromType = (value: number | string | Date) => {
if (typeof value === 'number') {
return debeziumTimeToDate(value);
}
return new Date(value);
};
export const safeJSONParse = <T>(json: string): T | undefined => {
try {
return JSON.parse(json);
} catch {
return undefined;
}
};
export function isNumber(value: string | number): boolean {
if (isNullOrUndefined(value)) {
return false;
}
if (!['string', 'number'].includes(typeof value)) {
return false;
}
if (typeof value === 'string' && value.trim().length === 0) {
return false;
}
return !isNaN(Number(value.toString()));
}
export const VALID_FOLDER_EMOJIS = [
`πΉ`,
'π',
'βοΈ',
'π₯',
'π¦',
'βοΈ',
'π',
'π³',
'π‘',
'π',
'π',
];
export const isOneValidEmoji = (text: string): boolean => {
return VALID_FOLDER_EMOJIS.includes(text);
};
export const validateWorkEmailDomain = (domain: string): boolean => {
const lowerCaseDomain = domain.toLowerCase();
return !!remoteConfig.vars.ignoredWorkEmailDomains?.some(
(ignoredDomain) => lowerCaseDomain === ignoredDomain,
);
};
export const unwrapArray = <T>(
arrayOrValue: T[] | T | undefined,
): T | undefined => {
if (Array.isArray(arrayOrValue)) {
return arrayOrValue[0];
}
return arrayOrValue;
};
export const parseBigInt = (value: bigint): number => {
try {
return Number(value);
} catch (originalError) {
const error = originalError as Error;
logger.error(
{ err: originalError, value: value?.toString() },
'failed parsing bigint',
);
throw error;
}
};
export const isSpecialUser = ({
userId,
}: {
userId?: string | null;
}): boolean => {
return !!userId && [ghostUser.id, systemUser.id].includes(userId);
};
export const getCurrencySymbol = ({
locale,
currency,
}: {
locale: string;
currency: string;
}) => {
return (0)
.toLocaleString(locale, {
style: 'currency',
currency: currency,
minimumFractionDigits: 0,
maximumFractionDigits: 0,
})
.replace(/\d/g, '')
.trim();
};
export const concatTextToNewline = (...args: Array<string | undefined>) =>
args.filter(Boolean).join(`\n`);
export const getBufferFromStream = async (
stream: NodeJS.ReadableStream,
): Promise<Buffer> => {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
stream.on('end', () => resolve(Buffer.concat(chunks)));
stream.on('error', (err) => reject(err));
});
};
export const textToSlug = (text: string): string =>
slugify(text, {
lower: true,
strict: true,
trim: true,
locale: 'en',
replacement: '-',
}).substring(0, 100);