fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
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
var mysql = require('mysql');
 
// Thunkify query methods
function wrapQueryMethod(fn, ctx) {
    return function() {
        // Obtain function arguments
        var args = [].slice.call(arguments);
        
        // Return a thunkified function that receives a done callback
        return function(done) {
            // Add a custom callback to provided args
            args.push(function(err, result) {
                // Query failed?
                if (err) {
                    return done(err);
                }
 
                // Query succeeded
                done(null, result);
            });
 
            // Execute the query
            fn.apply(ctx, args);
        };
    };
}
 
// Wrap a MySQL connection object's query methods
function wrapConnection(conn) {
    // Already wrapped this function?
    if (conn._coWrapped) {
        return conn;
    }
        
    // Set flag to avoid re-wrapping
    conn._coWrapped = true;
 
    // Functions to thunkify
    var queryMethods = [
        'query',
        'execute'
    ];
    
    // Traverse query methods list
    queryMethods.forEach(function(name) {
        // Thunkify the method
        conn[name] = wrapQueryMethod(conn[name], conn);
    });
    
    // Return co-friendly connection
    return conn;
}
 
module.exports = {
    createConnection: function(opts) {
        // Wrap createConnectionfunction
        return wrapConnection(mysql.createConnection(opts));
    },
 
    createPool: function(opts) {
        // Wrap createPool function
        return wrapConnection(mysql.createPool(opts));
    }
};