fork of hey-api/openapi-ts because I need some additional things
1import type { FileInfo, JSONSchema, Plugin } from '../types';
2
3export interface PluginResult {
4 error?: any;
5 plugin: Pick<Plugin, 'handler'>;
6 result?: string | Buffer | JSONSchema;
7}
8
9/**
10 * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
11 * Each method can return a synchronous value, a Promise, or call an error-first callback.
12 * If the promise resolves successfully, or the callback is called without an error, then the result
13 * is immediately returned and no further plugins are called.
14 * If the promise rejects, or the callback is called with an error, then the next plugin is called.
15 * If ALL plugins fail, then the last error is thrown.
16 */
17export async function run(plugins: Pick<Plugin, 'handler'>[], file: FileInfo) {
18 let index = 0;
19 let lastError: PluginResult;
20 let plugin: Pick<Plugin, 'handler'>;
21
22 return new Promise<PluginResult>((resolve, reject) => {
23 const runNextPlugin = async () => {
24 plugin = plugins[index++]!;
25
26 if (!plugin) {
27 // there are no more functions, re-throw the last error
28 return reject(lastError);
29 }
30
31 try {
32 const result = await plugin.handler(file);
33
34 if (result !== undefined) {
35 return resolve({
36 plugin,
37 result,
38 });
39 }
40
41 if (index === plugins.length) {
42 throw new Error('No promise has been returned.');
43 }
44 } catch (error) {
45 lastError = {
46 error,
47 plugin,
48 };
49 runNextPlugin();
50 }
51 };
52
53 runNextPlugin();
54 });
55}