ag-common 0.0.319 → 0.0.322

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.
@@ -7,9 +7,7 @@ export declare const putDynamo: <T>(item: T, tableName: string) => Promise<{
7
7
  data?: T | undefined;
8
8
  }>;
9
9
  export declare const batchWrite: <T extends {}>(tableName: string, itemsIn: T[], breakOnError?: boolean) => Promise<{
10
- error: string;
11
- } | {
12
- error?: undefined;
10
+ error?: string | undefined;
13
11
  }>;
14
12
  export declare const batchDelete: ({ tableName, breakOnError, pkName, keys, rangeName, rangeKeys, }: {
15
13
  pkName: string;
@@ -33,10 +33,8 @@ const putDynamo = (item, tableName) => __awaiter(void 0, void 0, void 0, functio
33
33
  (0, log_1.info)(`running dynamo put=${JSON.stringify(params, null, 2)}`);
34
34
  // write the todo to the database
35
35
  const put = yield exports.dynamoDb.put(params).promise();
36
- if (put.$response.error &&
37
- put.$response.error.statusCode &&
38
- put.$response.error.statusCode >= 400) {
39
- throw new Error(put.$response.error.message);
36
+ if (put.$response.error && put.$response.error.statusCode) {
37
+ return { error: put.$response.error.message };
40
38
  }
41
39
  // put never returns into, so just use what we have already
42
40
  return { data: item };
@@ -53,6 +51,9 @@ let batchWriteRaw = (req) => __awaiter(void 0, void 0, void 0, function* () {
53
51
  RequestItems: req,
54
52
  })
55
53
  .promise();
54
+ if (res.$response.error) {
55
+ throw new Error(res.$response.error.message);
56
+ }
56
57
  return res;
57
58
  }
58
59
  catch (e) {
@@ -153,9 +154,7 @@ const scan = (tableName) => __awaiter(void 0, void 0, void 0, function* () {
153
154
  .scan({ TableName: tableName, ExclusiveStartKey })
154
155
  .promise();
155
156
  ExclusiveStartKey = LastEvaluatedKey;
156
- if ($response.error &&
157
- $response.error.statusCode &&
158
- $response.error.statusCode >= 400) {
157
+ if ($response.error && $response.error.statusCode) {
159
158
  throw new Error($response.error.message);
160
159
  }
161
160
  if (newitems) {
@@ -213,7 +212,7 @@ const getItemsDynamo = ({ tableName, items, }) => __awaiter(void 0, void 0, void
213
212
  });
214
213
  exports.getItemsDynamo = getItemsDynamo;
215
214
  const queryDynamo = ({ tableName, pkName, pkValue, pkOperator = '=', skName, skValue, skOperator = '=', indexName, count = 1000, startKey: startKeyIn, filterName, filterValue, filterOperator = '=', sortAscending = true, }) => __awaiter(void 0, void 0, void 0, function* () {
216
- var _g, _h;
215
+ var _g;
217
216
  let startKey = startKeyIn;
218
217
  let kce = `#${pkName.toLowerCase()} ${pkOperator} :${pkName.toLowerCase()}`;
219
218
  const ean = { [`#${pkName.toLowerCase()}`]: pkName };
@@ -293,7 +292,7 @@ const queryDynamo = ({ tableName, pkName, pkValue, pkOperator = '=', skName, skV
293
292
  throw e;
294
293
  }
295
294
  startKey = lek;
296
- if ($response.error && ((_g = $response.error.statusCode) !== null && _g !== void 0 ? _g : 0) >= 400) {
295
+ if ($response.error) {
297
296
  (0, log_1.error)('error. query params=', JSON.stringify(params));
298
297
  throw new Error($response.error.message);
299
298
  }
@@ -301,7 +300,7 @@ const queryDynamo = ({ tableName, pkName, pkValue, pkOperator = '=', skName, skV
301
300
  if (newitems) {
302
301
  Items.push(...newitems.map((r) => r));
303
302
  }
304
- if (count > 0 && ((_h = newitems === null || newitems === void 0 ? void 0 : newitems.length) !== null && _h !== void 0 ? _h : 0) >= count) {
303
+ if (count > 0 && ((_g = newitems === null || newitems === void 0 ? void 0 : newitems.length) !== null && _g !== void 0 ? _g : 0) >= count) {
305
304
  return { Items, startKey };
306
305
  }
307
306
  } while (startKey && Object.keys(startKey).length > 0);
@@ -311,7 +310,7 @@ exports.queryDynamo = queryDynamo;
311
310
  const getDynamoTtl = (days) => Math.ceil(new Date().getTime() / 1000) + days * 86400;
312
311
  exports.getDynamoTtl = getDynamoTtl;
313
312
  const wipeTable = (tableName) => __awaiter(void 0, void 0, void 0, function* () {
314
- var _j;
313
+ var _h;
315
314
  const dbRaw = new dynamodb_1.default({ apiVersion: '2012-10-08' });
316
315
  let infoV = yield dbRaw
317
316
  .describeTable({
@@ -326,7 +325,7 @@ const wipeTable = (tableName) => __awaiter(void 0, void 0, void 0, function* ()
326
325
  TableName: tableName,
327
326
  })
328
327
  .promise();
329
- (0, log_1.warn)(`will delete ${(_j = all === null || all === void 0 ? void 0 : all.Items) === null || _j === void 0 ? void 0 : _j.length} items from ${tableName}`);
328
+ (0, log_1.warn)(`will delete ${(_h = all === null || all === void 0 ? void 0 : all.Items) === null || _h === void 0 ? void 0 : _h.length} items from ${tableName}`);
330
329
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
331
330
  // @ts-ignore
332
331
  const datagr = (0, array_1.chunk)(all.Items, 25);
@@ -13,7 +13,9 @@ export declare const putS3Object: ({ Body, Bucket, Key, ContentType, }: {
13
13
  Body: string | Blob;
14
14
  Bucket: string;
15
15
  Key: string;
16
- }) => Promise<void>;
16
+ }) => Promise<{
17
+ error?: string;
18
+ }>;
17
19
  export declare const uploadFile: ({ Bucket, Key, Body, }: {
18
20
  Bucket: string;
19
21
  Key: string;
@@ -22,4 +24,6 @@ export declare const uploadFile: ({ Bucket, Key, Body, }: {
22
24
  export declare const deleteFile: ({ Bucket, Key, }: {
23
25
  Bucket: string;
24
26
  Key: string;
25
- }) => Promise<void>;
27
+ }) => Promise<{
28
+ error?: string;
29
+ }>;
@@ -25,7 +25,7 @@ const getS3Object = ({ fileurl, }) => __awaiter(void 0, void 0, void 0, function
25
25
  });
26
26
  exports.getS3Object = getS3Object;
27
27
  const putS3Object = ({ Body, Bucket, Key, ContentType, }) => __awaiter(void 0, void 0, void 0, function* () {
28
- yield s3
28
+ const r = yield s3
29
29
  .putObject({
30
30
  Body,
31
31
  Bucket,
@@ -33,6 +33,10 @@ const putS3Object = ({ Body, Bucket, Key, ContentType, }) => __awaiter(void 0, v
33
33
  ContentType,
34
34
  })
35
35
  .promise();
36
+ if (r.$response.error) {
37
+ return { error: r.$response.error.message };
38
+ }
39
+ return {};
36
40
  });
37
41
  exports.putS3Object = putS3Object;
38
42
  const uploadFile = ({ Bucket, Key, Body, }) => __awaiter(void 0, void 0, void 0, function* () {
@@ -43,7 +47,8 @@ exports.uploadFile = uploadFile;
43
47
  const deleteFile = ({ Bucket, Key, }) => __awaiter(void 0, void 0, void 0, function* () {
44
48
  const res = yield s3.deleteObject({ Bucket, Key }).promise();
45
49
  if (res.$response.error) {
46
- throw res.$response.error;
50
+ return { error: res.$response.error.message };
47
51
  }
52
+ return {};
48
53
  });
49
54
  exports.deleteFile = deleteFile;
@@ -8,5 +8,9 @@ export interface ISendEmail {
8
8
  sourceArn: string;
9
9
  from: string;
10
10
  }
11
- export declare const sendEmail: ({ to, message, subject, sourceArn, from, }: ISendEmail) => Promise<void>;
12
- export declare const sendEmails: (emails: ISendEmail[]) => Promise<void[]>;
11
+ export declare const sendEmail: ({ to, message, subject, sourceArn, from, }: ISendEmail) => Promise<{
12
+ error?: string;
13
+ }>;
14
+ export declare const sendEmails: (emails: ISendEmail[]) => Promise<{
15
+ error?: string | undefined;
16
+ }[]>;
@@ -20,6 +20,7 @@ const setSes = (region) => {
20
20
  };
21
21
  exports.setSes = setSes;
22
22
  const sendEmail = ({ to, message, subject, sourceArn, from, }) => __awaiter(void 0, void 0, void 0, function* () {
23
+ var _a;
23
24
  // Create sendEmail params
24
25
  const params = {
25
26
  Destination: {
@@ -42,7 +43,11 @@ const sendEmail = ({ to, message, subject, sourceArn, from, }) => __awaiter(void
42
43
  ReplyToAddresses: [from],
43
44
  SourceArn: sourceArn,
44
45
  };
45
- yield exports.ses.sendEmail(params).promise();
46
+ const res = yield exports.ses.sendEmail(params).promise();
47
+ if (res.$response.error) {
48
+ return { error: (_a = res.$response.error) === null || _a === void 0 ? void 0 : _a.message };
49
+ }
50
+ return {};
46
51
  });
47
52
  exports.sendEmail = sendEmail;
48
53
  const sendEmails = (emails) => __awaiter(void 0, void 0, void 0, function* () { return Promise.all(emails.map(exports.sendEmail)); });
@@ -1,4 +1,6 @@
1
1
  import SQS from 'aws-sdk/clients/sqs';
2
2
  export declare let sqs: SQS;
3
3
  export declare const setSqs: (region: string) => void;
4
- export declare const sendMessages: <T>(items: T[], queueUrl: string) => Promise<void>;
4
+ export declare const sendMessages: <T>(items: T[], queueUrl: string) => Promise<{
5
+ error?: string;
6
+ }>;
@@ -30,10 +30,9 @@ const sendMessages = (items, queueUrl) => __awaiter(void 0, void 0, void 0, func
30
30
  })),
31
31
  };
32
32
  const put = yield exports.sqs.sendMessageBatch(req).promise();
33
- if (put.$response.error &&
34
- put.$response.error.statusCode &&
35
- put.$response.error.statusCode >= 400) {
36
- throw new Error(put.$response.error.message);
33
+ if (put.$response.error && put.$response.error.statusCode) {
34
+ return { error: put.$response.error.message };
37
35
  }
36
+ return {};
38
37
  });
39
38
  exports.sendMessages = sendMessages;
@@ -3,7 +3,21 @@ export declare const addHours: (d: number, h: number) => Date;
3
3
  export declare const addDays: (dIn: Date, count: number) => Date;
4
4
  export declare const addMinutes: (date: Date, minutes: number) => Date;
5
5
  export declare const lastDayInMonth: (date: Date) => Date;
6
- export declare const dateDiffDays: (date1: Date, date2: Date) => number;
6
+ /**
7
+ * breaks ticks into time diffs
8
+ * @param lowDate
9
+ * @param highDate defaults to Date.Now
10
+ * @returns
11
+ */
12
+ export declare const dateDiff: (lowDate: Date, highDate?: Date) => {
13
+ totalMinutes: number;
14
+ totalHours: number;
15
+ totalDays: number;
16
+ totalYears: number;
17
+ };
18
+ /**
19
+ * convert csharp datetime to js datetime
20
+ */
7
21
  export declare const CSharpToJs: (charpTicks: number) => Date;
8
22
  /**
9
23
  *
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.dateTimeToNearestMinute = exports.CSharpToJs = exports.dateDiffDays = exports.lastDayInMonth = exports.addMinutes = exports.addDays = exports.addHours = exports.getTimeSeconds = void 0;
3
+ exports.dateTimeToNearestMinute = exports.CSharpToJs = exports.dateDiff = exports.lastDayInMonth = exports.addMinutes = exports.addDays = exports.addHours = exports.getTimeSeconds = void 0;
4
+ const math_1 = require("./math");
4
5
  const getTimeSeconds = () => Math.ceil(new Date().getTime() / 1000);
5
6
  exports.getTimeSeconds = getTimeSeconds;
6
7
  const addHours = (d, h) => {
@@ -17,14 +18,24 @@ const addMinutes = (date, minutes) => new Date(date.getTime() + minutes * 60000)
17
18
  exports.addMinutes = addMinutes;
18
19
  const lastDayInMonth = (date) => new Date(date.getFullYear(), date.getMonth() + 1, 0);
19
20
  exports.lastDayInMonth = lastDayInMonth;
20
- const dateDiffDays = (date1, date2) => {
21
- const dt1 = new Date(date1);
22
- const dt2 = new Date(date2);
23
- return Math.floor((Date.UTC(dt2.getFullYear(), dt2.getMonth(), dt2.getDate()) -
24
- Date.UTC(dt1.getFullYear(), dt1.getMonth(), dt1.getDate())) /
25
- 1000);
21
+ /**
22
+ * breaks ticks into time diffs
23
+ * @param lowDate
24
+ * @param highDate defaults to Date.Now
25
+ * @returns
26
+ */
27
+ const dateDiff = (lowDate, highDate) => {
28
+ const ticksSince = (highDate !== null && highDate !== void 0 ? highDate : new Date()).getTime() - lowDate.getTime();
29
+ const totalMinutes = (0, math_1.toFixedDown)(ticksSince / 1000 / 60, 0);
30
+ const totalHours = (0, math_1.toFixedDown)(totalMinutes / 60, 0);
31
+ const totalDays = (0, math_1.toFixedDown)(totalHours / 24, 0);
32
+ const totalYears = (0, math_1.toFixedDown)(totalDays / 365, 0);
33
+ return { totalMinutes, totalHours, totalDays, totalYears };
26
34
  };
27
- exports.dateDiffDays = dateDiffDays;
35
+ exports.dateDiff = dateDiff;
36
+ /**
37
+ * convert csharp datetime to js datetime
38
+ */
28
39
  const CSharpToJs = (charpTicks) => {
29
40
  // ticks are in nanotime; convert to microtime
30
41
  const ticks = charpTicks / 10000;
@@ -61,3 +61,4 @@ export declare const chunkString: (str: string, length: number) => string[];
61
61
  */
62
62
  export declare function stringToObject(raw: string, splitKeyValue: string, splitKeys: string): Record<string, string>;
63
63
  export declare const indexOfNumber: (str: string, char: string, num?: number) => number | undefined;
64
+ export declare function isValidUrl(raw: string): boolean;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.indexOfNumber = exports.stringToObject = exports.chunkString = exports.safeStringify = exports.containsInsensitive = exports.containsInsensitiveIndex = exports.replaceRemove = exports.toTitleCase = exports.niceUrl = exports.truncate = exports.trim = exports.trimSide = exports.csvJSON = exports.fromBase64 = exports.toBase64 = void 0;
3
+ exports.isValidUrl = exports.indexOfNumber = exports.stringToObject = exports.chunkString = exports.safeStringify = exports.containsInsensitive = exports.containsInsensitiveIndex = exports.replaceRemove = exports.toTitleCase = exports.niceUrl = exports.truncate = exports.trim = exports.trimSide = exports.csvJSON = exports.fromBase64 = exports.toBase64 = void 0;
4
4
  const toBase64 = (str) => Buffer.from(str).toString('base64');
5
5
  exports.toBase64 = toBase64;
6
6
  const fromBase64 = (str) => Buffer.from(decodeURIComponent(str), 'base64').toString();
@@ -197,3 +197,14 @@ const indexOfNumber = (str, char, num = 0) => {
197
197
  return ret;
198
198
  };
199
199
  exports.indexOfNumber = indexOfNumber;
200
+ function isValidUrl(raw) {
201
+ let url;
202
+ try {
203
+ url = new URL(raw);
204
+ }
205
+ catch (_) {
206
+ return false;
207
+ }
208
+ return url.protocol === 'http:' || url.protocol === 'https:';
209
+ }
210
+ exports.isValidUrl = isValidUrl;
@@ -1,2 +1,8 @@
1
- export declare const daydiffstr: (dayticks: number) => string;
1
+ /**
2
+ * returns appropriate time diff string
3
+ * @param lowDate
4
+ * @param highDate defaults to Date.Now
5
+ * @returns
6
+ */
7
+ export declare const dateDiffToString: (lowDate: Date, highDate?: Date) => string;
2
8
  export declare const getDMY: (date: Date, dayOffset?: number) => string;
@@ -1,28 +1,32 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDMY = exports.daydiffstr = void 0;
3
+ exports.getDMY = exports.dateDiffToString = void 0;
4
4
  const plural_1 = require("./plural");
5
5
  const date_1 = require("../../common/helpers/date");
6
- const math_1 = require("../../common/helpers/math");
7
- const daydiffstr = (dayticks) => {
8
- const ticksSince = new Date().getTime() - dayticks;
9
- const totalMinutes = (0, math_1.toFixedDown)(ticksSince / 1000 / 60, 0);
10
- const totalHours = (0, math_1.toFixedDown)(totalMinutes / 60, 0);
11
- const totalDays = (0, math_1.toFixedDown)(totalHours / 24, 0);
12
- const totalYears = (0, math_1.toFixedDown)(totalDays / 365, 0);
13
- let ts = `${totalYears} ${(0, plural_1.plural)('yr', totalYears)} ago `;
14
- if (totalMinutes < 60) {
15
- ts = `${totalMinutes} ${(0, plural_1.plural)('min', totalMinutes)} ago `;
6
+ /**
7
+ * returns appropriate time diff string
8
+ * @param lowDate
9
+ * @param highDate defaults to Date.Now
10
+ * @returns
11
+ */
12
+ const dateDiffToString = (lowDate, highDate) => {
13
+ if (!lowDate) {
14
+ return '';
16
15
  }
17
- else if (totalHours < 24) {
18
- ts = `${totalHours} ${(0, plural_1.plural)('hr', totalHours)} ago `;
16
+ const d = (0, date_1.dateDiff)(lowDate, highDate !== null && highDate !== void 0 ? highDate : new Date());
17
+ let ts = `${d.totalYears} ${(0, plural_1.plural)('yr', d.totalYears)} ago `;
18
+ if (d.totalMinutes < 60) {
19
+ ts = `${d.totalMinutes} ${(0, plural_1.plural)('min', d.totalMinutes)} ago `;
19
20
  }
20
- else if (totalDays < 365) {
21
- ts = `${totalDays} ${(0, plural_1.plural)('day', totalDays)} ago `;
21
+ else if (d.totalHours < 24) {
22
+ ts = `${d.totalHours} ${(0, plural_1.plural)('hr', d.totalHours)} ago `;
23
+ }
24
+ else if (d.totalDays < 365) {
25
+ ts = `${d.totalDays} ${(0, plural_1.plural)('day', d.totalDays)} ago `;
22
26
  }
23
27
  return ts;
24
28
  };
25
- exports.daydiffstr = daydiffstr;
29
+ exports.dateDiffToString = dateDiffToString;
26
30
  const getDMY = (date, dayOffset) => {
27
31
  const date1 = (0, date_1.addDays)(date, dayOffset || 0);
28
32
  const d = String(date1.getDate()).padStart(2, '0');
@@ -4,7 +4,7 @@ exports.UseLocalStorage = exports.getLocalStorageItem = exports.setLocalStorageI
4
4
  const log_1 = require("../../common/helpers/log");
5
5
  const object_1 = require("../../common/helpers/object");
6
6
  const react_1 = require("react");
7
- const getTimeSeconds = () => Math.ceil(new Date().getTime() / 1000);
7
+ const date_1 = require("../../common/helpers/date");
8
8
  const clearLocalStorageItem = (key) => {
9
9
  if (typeof window === 'undefined') {
10
10
  return;
@@ -41,7 +41,7 @@ const setLocalStorageItem = (key, value, ttl) => {
41
41
  return;
42
42
  }
43
43
  const set = {
44
- expiry: !ttl ? undefined : getTimeSeconds() + ttl,
44
+ expiry: !ttl ? undefined : (0, date_1.getTimeSeconds)() + ttl,
45
45
  val: JSON.stringify(value),
46
46
  };
47
47
  window.localStorage.setItem(key, JSON.stringify(set));
@@ -58,7 +58,7 @@ const getLocalStorageItem = (key, initialValue, ttl) => {
58
58
  }
59
59
  const itemraw = window.localStorage.getItem(key);
60
60
  const item = (0, object_1.tryJsonParse)(itemraw, undefined);
61
- if (!item || (item.expiry && getTimeSeconds() > item.expiry)) {
61
+ if (!item || (item.expiry && (0, date_1.getTimeSeconds)() > item.expiry)) {
62
62
  (0, exports.setLocalStorageItem)(key, initialValue, ttl);
63
63
  return initialValue;
64
64
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.319",
3
+ "version": "0.0.322",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "author": "Andrei Gec <@andreigec> (https://gec.dev/)",