Skip to content

Commit

Permalink
try to use safely-retry as local file
Browse files Browse the repository at this point in the history
  • Loading branch information
ratchapol-an committed Feb 19, 2025
1 parent c6b0c67 commit 2a04df9
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
1 change: 0 additions & 1 deletion packages/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
],
"dependencies": {
"axios": "^1.7.9",
"safely-try": "^1.1.0",
"tslib": "^2.8.1",
"uuid": "^11.0.5"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/lib/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { v1 as uuidv1 } from 'uuid';
import os from 'os';
import fs from 'fs';
import { spawnSync } from 'child_process';
import safelyTry from 'safely-try';
import safelyTry from './safely-retry.js';
import axios from 'axios';

const UNKNOWN_VALUE = '<unknown>';
Expand Down
42 changes: 42 additions & 0 deletions packages/common/src/lib/safely-retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-explicit-any */
function isPromise<T, S>(obj: PromiseLike<T> | S): obj is PromiseLike<T> {
return (
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
'then' in obj &&
typeof obj.then === 'function'
);
}

function safelyTry<T, E = Error>(
fn: ((...args: any[]) => T) | (() => T),
...args: any[]
): T extends PromiseLike<any>
?
| Promise<{ data: undefined; error: E }>
| Promise<{ data: Awaited<T>; error: undefined }>
: { data: undefined; error: E } | { data: T; error: undefined } {
try {
// try calling the function
const x = fn(...args);

// asynchronous functions
if (isPromise(x)) {
// @ts-ignore
return Promise.resolve(x).then(
(value) => ({ data: value as Awaited<T>, error: undefined }),
(error) => ({ data: undefined, error: error as E }),
);
}

// synchronous functions
// @ts-ignore
return { data: x, error: undefined };
} catch (error) {
// @ts-ignore
return { data: undefined, error: error as E };
}
}

export default safelyTry;

0 comments on commit 2a04df9

Please sign in to comment.