wip:milestone 0 fixes
Some checks failed
CI/CD Pipeline / unit-tests (push) Failing after 1m16s
CI/CD Pipeline / integration-tests (push) Failing after 2m32s
CI/CD Pipeline / lint (push) Successful in 5m22s
CI/CD Pipeline / e2e-tests (push) Has been skipped
CI/CD Pipeline / build (push) Has been skipped

This commit is contained in:
2026-03-15 12:35:42 +02:00
parent 6708cf28a7
commit cffdf8af86
61266 changed files with 4511646 additions and 1938 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Artem Zakharchenko
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,150 @@
[![Latest release](https://img.shields.io/npm/v/@open-draft/until.svg)](https://www.npmjs.com/package/@open-draft/until)
# `until`
Gracefully handle a Promise using `async`/`await`.
## Why?
With the addition of `async`/`await` keywords in ECMAScript 2017 the handling of Promises became much easier. However, one must keep in mind that the `await` keyword provides no standard error handling API. Consider this usage:
```js
function getUser(id) {
const data = await fetchUser(id)
// Work with "data"...
}
```
In case `fetchUser()` throws an error, the entire `getUser()` function's scope will terminate. Because of this, it's recommended to implement error handling using `try`/`catch` block wrapping `await` expressions:
```js
function getUser(id)
let data = null
try {
data = await asyncAction()
} catch (error) {
console.error(error)
}
// Work with "data"...
}
```
While this is a semantically valid approach, constructing `try`/`catch` around each awaited operation may be tedious and get overlooked at times. Such error handling also introduces separate closures for execution and error scenarios of an asynchronous operation.
This library encapsulates the `try`/`catch` error handling in a utility function that does not create a separate closure and exposes a NodeJS-friendly API to work with errors and resolved data.
## Getting started
### Install
```bash
npm install @open-draft/until
```
### Usage
```js
import { until } from '@open-draft/until'
async function(id) {
const { error, data } = await until(() => fetchUser(id))
if (error) {
return handleError(error)
}
return data
}
```
### Usage with TypeScript
```ts
import { until } from '@open-draft/until'
interface User {
firstName: string
age: number
}
interface UserFetchError {
type: 'FORBIDDEN' | 'NOT_FOUND'
message?: string
}
async function(id: string) {
const { error, data } = await until<UserFetchError, User>(() => fetchUser(id))
if (error) {
handleError(error.type, error.message)
}
return data.firstName
}
```
## Frequently asked questions
### Why does `until` accept a function and not a `Promise` directly?
This has been intentionally introduced to await a single logical unit as opposed to a single `Promise`.
```js
// Notice how a single "until" invocation can handle
// a rather complex piece of logic. This way any rejections
// or exceptions happening within the given function
// can be handled via the same "error".
const { error, data } = until(async () => {
const user = await fetchUser()
const nextUser = normalizeUser(user)
const transaction = await saveModel('user', user)
invariant(transaction.status === 'OK', 'Saving user failed')
return transaction.result
})
if (error) {
// Handle any exceptions happened within the function.
}
```
### Why does `until` return an object and not an array?
The `until` function used to return an array of shape `[error, data]` prior to `2.0.0`. That has been changed, however, to get proper type-safety using discriminated union type.
Compare these two examples:
```ts
const [error, data] = await until(() => action())
if (error) {
return null
}
// Data still has ambiguous "DataType | null" type here
// even after you've checked and handled the "error" above.
console.log(data)
```
```ts
const result = await until(() => action())
// At this point, "data" is ambiguous "DataType | null"
// which is correct, as you haven't checked nor handled the "error".
if (result.error) {
return null
}
// Data is strict "DataType" since you've handled the "error" above.
console.log(result.data)
```
> It's crucial to keep the entire result of the `Promise` in a single variable and not destructure it. TypeScript will always keep the type of `error` and `data` as it was upon destructuring, ignoring any type guards you may perform later on.
## Special thanks
- [giuseppegurgone](https://twitter.com/giuseppegurgone) for the discussion about the original `until` API.

View File

@@ -0,0 +1,15 @@
type AsyncTuple<ErrorType extends any = Error, DataType extends any = unknown> = {
error: ErrorType;
data: null;
} | {
error: null;
data: DataType;
};
/**
* Gracefully handles a given Promise factory.
* @example
* const { error, data } = await until(() => asyncAction())
*/
declare const until: <ErrorType extends unknown = Error, DataType extends unknown = unknown>(promise: () => Promise<DataType>) => Promise<AsyncTuple<ErrorType, DataType>>;
export { until };

View File

@@ -0,0 +1,41 @@
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
until: () => until
});
module.exports = __toCommonJS(src_exports);
// src/until.ts
var until = async (promise) => {
try {
const data = await promise().catch((error) => {
throw error;
});
return { error: null, data };
} catch (error) {
return { error, data: null };
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
until
});
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/index.ts","../src/until.ts"],"sourcesContent":["export { until } from './until'","export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise<DataType>,\n): Promise<AsyncTuple<ErrorType, DataType>> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,IAAM,QAAQ,OAInB,YAC6C;AAC7C,MAAI;AACF,UAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC5C,YAAM;AAAA,IACR,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B,SAAS,OAAP;AACA,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B;AACF;","names":[]}

View File

@@ -0,0 +1,15 @@
// src/until.ts
var until = async (promise) => {
try {
const data = await promise().catch((error) => {
throw error;
});
return { error: null, data };
} catch (error) {
return { error, data: null };
}
};
export {
until
};
//# sourceMappingURL=index.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/until.ts"],"sourcesContent":["export type AsyncTuple<\n ErrorType extends any = Error,\n DataType extends any = unknown,\n> =\n | {\n error: ErrorType\n data: null\n }\n | { error: null; data: DataType }\n\n/**\n * Gracefully handles a given Promise factory.\n * @example\n * const { error, data } = await until(() => asyncAction())\n */\nexport const until = async <\n ErrorType extends any = Error,\n DataType extends any = unknown,\n>(\n promise: () => Promise<DataType>,\n): Promise<AsyncTuple<ErrorType, DataType>> => {\n try {\n const data = await promise().catch((error) => {\n throw error\n })\n return { error: null, data }\n } catch (error) {\n return { error, data: null }\n }\n}\n"],"mappings":";AAeO,IAAM,QAAQ,OAInB,YAC6C;AAC7C,MAAI;AACF,UAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC,UAAU;AAC5C,YAAM;AAAA,IACR,CAAC;AACD,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B,SAAS,OAAP;AACA,WAAO,EAAE,OAAO,MAAM,KAAK;AAAA,EAC7B;AACF;","names":[]}

View File

@@ -0,0 +1,37 @@
{
"name": "@open-draft/until",
"version": "2.1.0",
"description": "Gracefully handle a Promise using async/await.",
"main": "./lib/index.js",
"module": "./lib/index.mjs",
"types": "./lib/index.d.ts",
"exports": {
".": {
"types": "./lib/index.d.ts",
"require": "./lib/index.js",
"import": "./lib/index.mjs",
"default": "./lib/index.mjs"
}
},
"repository": "open-draft/until",
"author": "Artem Zakharchenko <kettanaito@gmail.com>",
"license": "MIT",
"files": [
"README.md",
"lib"
],
"devDependencies": {
"@ossjs/release": "^0.5.1",
"@types/jest": "^26.0.22",
"jest": "^26.6.3",
"ts-jest": "^26.5.4",
"tsup": "^6.2.3",
"typescript": "^4.2.4"
},
"scripts": {
"start": "tsc -w",
"test": "jest",
"build": "tsup",
"release": "release publish"
}
}