forked from jbrumwell/mock-knex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (81 loc) · 1.89 KB
/
index.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
var _ = require('lodash');
var fs = require('fs');
var tracker = require('./lib/tracker');
var semver = require('semver');
var path = require('path');
var platforms = [
'knex',
];
function MockDb() {
this.adapter = null;
this._adapter = null;
}
MockDb.prototype.getTracker = function getTracker() {
return tracker;
};
MockDb.prototype.mock = function mock(db, adapter) {
if (adapter) {
this.setAdapter(adapter);
}
return this._adapter.mock(db);
};
MockDb.prototype.unmock = function unmock(db, adapter) {
if (adapter) {
this.setAdapter(adapter);
}
return this._adapter.unmock(db);
};
MockDb.prototype.setAdapter = function setAdapter(adapter) {
var parts;
var version;
var platform;
if (_.isString(adapter)) {
parts = adapter.split('@');
platform = parts[0];
version = parts[1];
if (platforms.indexOf(platform) === -1) {
throw new Error('invalid platform: ' + platform);
}
var versions = fs.readdirSync('./lib/platforms/' + platform);
versions = versions.sort(function(a, b) {
return a - b;
});
if (version) {
if (! semver.valid(version)) {
version += '.0';
}
versions.some(function(v) {
var found = 0;
if (semver.satisfies(version, '^' + v)) {
found = version = v;
}
return found > 0;
});
} else {
version = versions.pop();
}
this.adapter = {
platform: platform,
version: version,
};
} else {
this.adapter = adapter;
}
this._adapter = require(
path.join(
__dirname,
'./lib/platforms',
this.adapter.platform,
this.adapter.version
)
);
return this;
};
MockDb.prototype.getAdapter = function getAdapter() {
if (this._adapter === null) {
throw new Error('No Adapter has been set, see setAdapter');
}
return this._adapter;
};
module.exports = new MockDb();