保誠-保戶業務員媒合平台
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
'use strict';
 
const fs = require('graceful-fs');
 
function createSyncFs(fs) {
    const methods = ['mkdir', 'realpath', 'stat', 'rmdir', 'utimes'];
    const newFs = { ...fs };
 
    methods.forEach((method) => {
        newFs[method] = (...args) => {
            const callback = args.pop();
            let ret;
 
            try {
                ret = fs[`${method}Sync`](...args);
            } catch (err) {
                return callback(err);
            }
 
            callback(null, ret);
        };
    });
 
    return newFs;
}
 
// ----------------------------------------------------------
 
function toPromise(method) {
    return (...args) => new Promise((resolve, reject) => {
        args.push((err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
 
        method(...args);
    });
}
 
function toSync(method) {
    return (...args) => {
        let err;
        let result;
 
        args.push((_err, _result) => {
            err = _err;
            result = _result;
        });
 
        method(...args);
 
        if (err) {
            throw err;
        }
 
        return result;
    };
}
 
function toSyncOptions(options) {
    // Shallow clone options because we are oging to mutate them
    options = { ...options };
 
    // Transform fs to use the sync methods instead
    options.fs = createSyncFs(options.fs || fs);
 
    // Retries are not allowed because it requires the flow to be sync
    if (
        (typeof options.retries === 'number' && options.retries > 0) ||
        (options.retries && typeof options.retries.retries === 'number' && options.retries.retries > 0)
    ) {
        throw Object.assign(new Error('Cannot use retries with the sync api'), { code: 'ESYNC' });
    }
 
    return options;
}
 
module.exports = {
    toPromise,
    toSync,
    toSyncOptions,
};