├── .babelrc
├── index.js
├── .gitignore
├── src
├── logger.js
├── stores
│ ├── data.js
│ └── networkStore.js
├── bot.js
├── observer.js
├── utils.js
├── scorocode.js
├── websocket.js
├── messenger.js
├── user.js
├── cloudCode.js
├── client.js
├── httpRequest.js
├── object.js
├── protocol.js
├── instance.js
├── updateOps.js
├── bson.js
├── query.js
└── objectid.js
├── dist
├── logger.js
├── debugger.js
├── observer.js
├── stores
│ ├── data.js
│ └── networkStore.js
├── bot.js
├── utils.js
├── scorocode.js
├── websocket.js
├── messenger.js
├── client.js
├── cloudCode.js
├── user.js
├── httpRequest.js
├── bson.js
├── object.js
├── updateOps.js
├── instance.js
├── protocol.js
├── query.js
└── objectid.js
├── package.json
├── LICENSE
├── gulpfile.js
└── README.md
/.babelrc:
--------------------------------------------------------------------------------
1 | { "presets": ["es2015"] }
2 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | module.exports = require('./dist/scorocode.js');
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | node_modules
3 | app
4 | npm-debug.log
5 |
--------------------------------------------------------------------------------
/src/logger.js:
--------------------------------------------------------------------------------
1 | export class SCLogger {
2 | constructor(opt = {}) {
3 | this.log = function() {
4 | console.log.apply(this, arguments);
5 | };
6 | this.error = function () {
7 | console.error.apply(this, arguments);
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/stores/data.js:
--------------------------------------------------------------------------------
1 | import {Network} from './networkStore'
2 |
3 | export class DataStore {
4 | static getInstance(type) {
5 | let store;
6 | switch (type) {
7 | default:
8 | store = new Network();
9 | }
10 | return store;
11 | }
12 | }
--------------------------------------------------------------------------------
/src/bot.js:
--------------------------------------------------------------------------------
1 | import {BotProtocol} from './protocol'
2 | import {Utils} from './utils'
3 | import {HttpRequest} from './httpRequest'
4 |
5 | export class SCBot {
6 | constructor(botId) {
7 | this.botId = botId;
8 | }
9 |
10 | send(data, callbacks = {}) {
11 | const protocol = BotProtocol.init(this.botId);
12 | protocol.setData(data);
13 |
14 | const request = new HttpRequest(protocol);
15 | const promise = request.execute();
16 | return Utils.wrapCallbacks(promise, callbacks);
17 | }
18 | }
--------------------------------------------------------------------------------
/dist/logger.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8 |
9 | var SCLogger = exports.SCLogger = function SCLogger() {
10 | var opt = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
11 |
12 | _classCallCheck(this, SCLogger);
13 |
14 | this.log = function () {
15 | console.log.apply(this, arguments);
16 | };
17 | this.error = function () {
18 | console.error.apply(this, arguments);
19 | };
20 | };
--------------------------------------------------------------------------------
/dist/debugger.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8 |
9 | var SCDebugger = exports.SCDebugger = function SCDebugger() {
10 | var opt = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
11 |
12 | _classCallCheck(this, SCDebugger);
13 |
14 | this.log = function () {
15 | console.log.apply(this, arguments);
16 | };
17 | this.error = function () {
18 | console.error.apply(this, arguments);
19 | };
20 | };
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "scorocode",
3 | "version": "0.9.0",
4 | "description": "Scorocode Javascript SDK",
5 | "dependencies": {
6 | "bufferutil": "^1.2.1",
7 | "utf-8-validate": "^1.2.1",
8 | "ws": "^1.1.1"
9 | },
10 | "devDependencies": {
11 | "babel-preset-es2015": "^6.6.0",
12 | "babel-preset-stage-0": "^6.22.0",
13 | "babelify": "^7.3.0",
14 | "browserify": "^13.0.0",
15 | "gulp": "^3.9.1",
16 | "gulp-babel": "^6.1.2",
17 | "gulp-rename": "^1.2.2",
18 | "gulp-uglify": "^1.5.3",
19 | "vinyl-source-stream": "^1.1.0"
20 | },
21 | "scripts": {},
22 | "repository": {
23 | "type": "git",
24 | "url": "https://github.com/Scorocode/scorocode-SDK-JS"
25 | },
26 | "author": "Nikita Kortunov",
27 | "license": "MIT"
28 | }
29 |
--------------------------------------------------------------------------------
/src/observer.js:
--------------------------------------------------------------------------------
1 | var instance;
2 |
3 | function Observer () {
4 |
5 | if (instance) {
6 | return instance;
7 | }
8 |
9 | if (this && this.constructor === Observer) {
10 | instance = this;
11 | } else {
12 | return new Observer();
13 | }
14 |
15 | }
16 |
17 | Observer.prototype._listeners = {};
18 |
19 | Observer.prototype.emit = function () {
20 |
21 | var args = [];
22 | for (var i = 0; i < arguments.length; i++) {
23 | args[i] = arguments[i];
24 | }
25 |
26 | var e = args.shift();
27 |
28 | if (!this._listeners[e]) {
29 | return false;
30 | }
31 |
32 | let ln = this._listeners[e].length;
33 | for (let i = 0; i < ln; i++) {
34 | this._listeners[e][i].apply(null, args)
35 | }
36 |
37 | };
38 |
39 | Observer.prototype.on = function (e, cb) {
40 |
41 | if (!this._listeners[e]) {
42 | this._listeners[e] = [];
43 | }
44 | this._listeners[e].push(cb);
45 |
46 | };
47 |
48 | var SCObserver = (function () {
49 |
50 | return Observer;
51 |
52 | }());
53 |
54 | export default SCObserver;
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 Nikita Kortunov
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/gulpfile.js:
--------------------------------------------------------------------------------
1 | var browserify = require('browserify');
2 | var gulp = require('gulp');
3 | var babelify = require("babelify");
4 | var babel = require('gulp-babel');
5 | var source = require('vinyl-source-stream');
6 | var uglify = require('gulp-uglify');
7 | var rename = require('gulp-rename');
8 |
9 | gulp.task('compile', function () {
10 | return gulp.src('src/**/*.js')
11 | .pipe(babel())
12 | .pipe(gulp.dest('dist/'))
13 | });
14 |
15 | gulp.task('browserify', function () {
16 | var stream = browserify({
17 | builtins: ['_process', 'buffer'],
18 | entries: 'src/scorocode.js',
19 | standalone: 'Scorocode'
20 | })
21 | .ignore('_process')
22 | .transform("babelify", {presets: ["es2015"]})
23 | .bundle();
24 |
25 | return stream.pipe(source('scorocode.js'))
26 | .pipe(gulp.dest('./lib/browser/'));
27 | });
28 |
29 | gulp.task('minify', function() {
30 | return gulp.src('lib/browser/scorocode.js')
31 | .pipe(uglify())
32 | .pipe(rename({ extname: '.min.js' }))
33 | .pipe(gulp.dest('lib/browser/'))
34 | });
35 |
36 | gulp.task('default', ['compile', 'browserify', 'minify']);
--------------------------------------------------------------------------------
/dist/observer.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | var instance;
7 |
8 | function Observer() {
9 |
10 | if (instance) {
11 | return instance;
12 | }
13 |
14 | if (this && this.constructor === Observer) {
15 | instance = this;
16 | } else {
17 | return new Observer();
18 | }
19 | }
20 |
21 | Observer.prototype._listeners = {};
22 |
23 | Observer.prototype.emit = function () {
24 |
25 | var args = [];
26 | for (var i = 0; i < arguments.length; i++) {
27 | args[i] = arguments[i];
28 | }
29 |
30 | var e = args.shift();
31 |
32 | if (!this._listeners[e]) {
33 | return false;
34 | }
35 |
36 | var ln = this._listeners[e].length;
37 | for (var _i = 0; _i < ln; _i++) {
38 | this._listeners[e][_i].apply(null, args);
39 | }
40 | };
41 |
42 | Observer.prototype.on = function (e, cb) {
43 |
44 | if (!this._listeners[e]) {
45 | this._listeners[e] = [];
46 | }
47 | this._listeners[e].push(cb);
48 | };
49 |
50 | var SCObserver = function () {
51 |
52 | return Observer;
53 | }();
54 |
55 | exports.default = SCObserver;
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | var Utils = {};
2 | Utils.isNumber = function (obj) {
3 | return toString.call(obj) === '[object Number]';
4 | };
5 | Utils.isObject = function(obj) {
6 | var type = typeof obj;
7 | return type === 'function' || type === 'object' && !!obj;
8 | };
9 | Utils.isArray = Array.isArray || function(obj) {
10 | return toString.call(obj) === '[object Array]';
11 | };
12 | Utils.wrapCallbacks = function (promise, callbacks = {}) {
13 | return promise.then(data => {
14 | if (callbacks.success) {
15 | callbacks.success(data);
16 | }
17 | return data;
18 | }).catch(error => {
19 | if (callbacks.error) {
20 | callbacks.error(error);
21 | }
22 | return Promise.reject(error)
23 | });
24 | };
25 | Utils.extend = function (parent, child) {
26 | for (let prop in child) {
27 | parent[prop] = child[prop];
28 | }
29 | };
30 | Utils.removeElement = function (array, el) {
31 | let arr = array.filter((item) => {
32 | if (el !== item) {
33 | return el
34 | }
35 | });
36 |
37 | return arr;
38 | };
39 | Utils.promiseWhile = function(condition, body) {
40 | return new Promise((resolve, reject) => {
41 | function loop(res) {
42 | if (!condition(res)) return resolve();
43 | body(res).then(loop, reject);
44 | }
45 | loop();
46 | });
47 | };
48 |
49 |
50 | export {Utils}
--------------------------------------------------------------------------------
/dist/stores/data.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.DataStore = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _networkStore = require('./networkStore');
11 |
12 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13 |
14 | var DataStore = exports.DataStore = function () {
15 | function DataStore() {
16 | _classCallCheck(this, DataStore);
17 | }
18 |
19 | _createClass(DataStore, null, [{
20 | key: 'getInstance',
21 | value: function getInstance(type) {
22 | var store = void 0;
23 | switch (type) {
24 | default:
25 | store = new _networkStore.Network();
26 | }
27 | return store;
28 | }
29 | }]);
30 |
31 | return DataStore;
32 | }();
--------------------------------------------------------------------------------
/src/scorocode.js:
--------------------------------------------------------------------------------
1 | import { SCQuery } from './query';
2 | import { SCUser } from './user';
3 | import { SCObject } from './object';
4 | import { Client } from './client';
5 | import {SCUpdateOps} from './updateOps'
6 | import {SCMessenger} from './messenger'
7 | import {SCCloudCode} from './cloudCode'
8 | import {SCWebSocket} from './websocket'
9 | import {SCSystem, SCField} from './system'
10 | import {SCLogger} from './logger'
11 | import {SCBot} from './bot'
12 | import {SCInstance} from './instance'
13 | import SCObserver from './observer'
14 |
15 | var Scorocode = {
16 | Init: function (opt) {
17 | const client = Client.init(opt);
18 | return client;
19 | },
20 | getSessionId: function() {
21 | const client = Client.getInstance();
22 | return client.sessionId;
23 | },
24 | setSessionId: function(sessionId) {
25 | const client = Client.getInstance();
26 | client.sessionId = sessionId;
27 | },
28 | on: function (e, cb) {
29 | SCObserver().on(e, cb);
30 | },
31 | use: function (cb) {
32 | const client = Client.getInstance();
33 | client.middleware.push(cb);
34 | }
35 | };
36 |
37 | Scorocode.Query = SCQuery;
38 | Scorocode.Object = SCObject;
39 | Scorocode.User = SCUser;
40 | Scorocode.UpdateOps = SCUpdateOps;
41 | Scorocode.Messenger = SCMessenger;
42 | Scorocode.CloudCode = SCCloudCode;
43 | Scorocode.WebSocket = SCWebSocket;
44 | Scorocode.System = SCSystem;
45 | Scorocode.Logger = SCLogger;
46 | Scorocode.Bot = SCBot;
47 | Scorocode.Instance = SCInstance;
48 | Scorocode.Field = SCField;
49 |
50 | module.exports = Scorocode;
--------------------------------------------------------------------------------
/dist/bot.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCBot = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _protocol = require('./protocol');
11 |
12 | var _utils = require('./utils');
13 |
14 | var _httpRequest = require('./httpRequest');
15 |
16 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17 |
18 | var SCBot = exports.SCBot = function () {
19 | function SCBot(botId) {
20 | _classCallCheck(this, SCBot);
21 |
22 | this.botId = botId;
23 | }
24 |
25 | _createClass(SCBot, [{
26 | key: 'send',
27 | value: function send(data) {
28 | var callbacks = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
29 |
30 | var protocol = _protocol.BotProtocol.init(this.botId);
31 | protocol.setData(data);
32 |
33 | var request = new _httpRequest.HttpRequest(protocol);
34 | var promise = request.execute();
35 | return _utils.Utils.wrapCallbacks(promise, callbacks);
36 | }
37 | }]);
38 |
39 | return SCBot;
40 | }();
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # scorocode-sdk-js
2 | SDK предоставляет доступ к платформе Scorocode для построения приложений, основанных на JavaScript
3 | Подробности на нашем сайте: https://scorocode.ru
4 |
5 | ### Установка
6 | Для использования SDK на стороне браузера, скачайте библиотеку `lib/browser/scorocode.min.js` и подключите ее в проекте:
7 | ```
8 |
9 | ```
10 |
11 |
12 | Для использования SDK на стороне сервера (NodeJS) установите модуль SDK `npm install scorocode` и подключите его в проекте:
13 | ```
14 | var Scorocode = require('scorocode');
15 | ```
16 |
17 | ### License
18 | ```
19 | MIT License
20 |
21 | Copyright (c) 2016 ProfIT-Ventures LLC
22 |
23 | Permission is hereby granted, free of charge, to any person obtaining a copy
24 | of this software and associated documentation files (the "Software"), to deal
25 | in the Software without restriction, including without limitation the rights
26 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
27 | copies of the Software, and to permit persons to whom the Software is
28 | furnished to do so, subject to the following conditions:
29 |
30 | The above copyright notice and this permission notice shall be included in all
31 | copies or substantial portions of the Software.
32 |
33 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
34 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
35 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
36 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
37 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
38 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
39 | SOFTWARE.
40 | ```
41 |
--------------------------------------------------------------------------------
/dist/utils.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
8 |
9 | var Utils = {};
10 | Utils.isNumber = function (obj) {
11 | return toString.call(obj) === '[object Number]';
12 | };
13 | Utils.isObject = function (obj) {
14 | var type = typeof obj === 'undefined' ? 'undefined' : _typeof(obj);
15 | return type === 'function' || type === 'object' && !!obj;
16 | };
17 | Utils.isArray = Array.isArray || function (obj) {
18 | return toString.call(obj) === '[object Array]';
19 | };
20 | Utils.wrapCallbacks = function (promise) {
21 | var callbacks = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
22 |
23 | return promise.then(function (data) {
24 | if (callbacks.success) {
25 | callbacks.success(data);
26 | }
27 | return data;
28 | }).catch(function (error) {
29 | if (callbacks.error) {
30 | callbacks.error(error);
31 | }
32 | return Promise.reject(error);
33 | });
34 | };
35 | Utils.extend = function (parent, child) {
36 | for (var prop in child) {
37 | parent[prop] = child[prop];
38 | }
39 | };
40 | Utils.removeElement = function (array, el) {
41 | var arr = array.filter(function (item) {
42 | if (el !== item) {
43 | return el;
44 | }
45 | });
46 |
47 | return arr;
48 | };
49 | Utils.promiseWhile = function (condition, body) {
50 | return new Promise(function (resolve, reject) {
51 | function loop(res) {
52 | if (!condition(res)) return resolve();
53 | body(res).then(loop, reject);
54 | }
55 | loop();
56 | });
57 | };
58 |
59 | exports.Utils = Utils;
--------------------------------------------------------------------------------
/src/websocket.js:
--------------------------------------------------------------------------------
1 | import { Client } from './client';
2 |
3 | export class SCWebSocket {
4 | constructor(chanName, options = {}) {
5 | var self = this;
6 |
7 | if (!chanName) {
8 | throw new Error('Channel name is empty');
9 | }
10 |
11 | var cl = Client.getInstance();
12 | const ws = cl.isNode ? require('ws') : WebSocket;
13 |
14 | let AppId = cl.applicationID;
15 | let wsKey = cl.websocketKey;
16 | let host = cl.get('WSHOST');
17 | let protocol = cl.get('WS_PROTOCOL');
18 |
19 | this.wsInstanse = new ws(protocol+'://' + host + '/' + AppId + '/' + wsKey + '/' + chanName);
20 | this._handlers = {};
21 |
22 | this.wsInstanse.onclose = function (event) {
23 | self._emit('close', {
24 | wasClean: event.wasClean,
25 | code: event.code,
26 | reason: event.reason
27 | });
28 | };
29 | this.wsInstanse.onerror = function (error) {
30 | self._emit('error', error);
31 | };
32 | this.wsInstanse.onmessage = function (event) {
33 | self._emit('message', event.data);
34 | };
35 | this.wsInstanse.onopen = function () {
36 | self._emit('open');
37 | };
38 | }
39 | _emit () {
40 |
41 | let args = [];
42 | for (let i = 0; i < arguments.length; i++) {
43 | args[i] = arguments[i];
44 | }
45 |
46 | let ev = args.shift();
47 |
48 | if (!this._handlers[ev]) {
49 | this._handlers[ev] = [];
50 | }
51 |
52 | let ln = this._handlers[ev].length;
53 |
54 | for (let i = 0; i < ln; i++) {
55 | this._handlers[ev][i].apply(null, args);
56 | }
57 | }
58 | on (ev, cb) {
59 | if (!this._handlers[ev]) {
60 | this._handlers[ev] = [];
61 | }
62 |
63 | this._handlers[ev].push(cb);
64 | }
65 | send (msg) {
66 | this.wsInstanse.send(msg);
67 | }
68 | }
--------------------------------------------------------------------------------
/dist/scorocode.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var _query = require('./query');
4 |
5 | var _user = require('./user');
6 |
7 | var _object = require('./object');
8 |
9 | var _client = require('./client');
10 |
11 | var _updateOps = require('./updateOps');
12 |
13 | var _messenger = require('./messenger');
14 |
15 | var _cloudCode = require('./cloudCode');
16 |
17 | var _websocket = require('./websocket');
18 |
19 | var _system = require('./system');
20 |
21 | var _logger = require('./logger');
22 |
23 | var _bot = require('./bot');
24 |
25 | var _instance = require('./instance');
26 |
27 | var _observer = require('./observer');
28 |
29 | var _observer2 = _interopRequireDefault(_observer);
30 |
31 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
32 |
33 | var Scorocode = {
34 | Init: function Init(opt) {
35 | var client = _client.Client.init(opt);
36 | return client;
37 | },
38 | getSessionId: function getSessionId() {
39 | var client = _client.Client.getInstance();
40 | return client.sessionId;
41 | },
42 | setSessionId: function setSessionId(sessionId) {
43 | var client = _client.Client.getInstance();
44 | client.sessionId = sessionId;
45 | },
46 | on: function on(e, cb) {
47 | (0, _observer2.default)().on(e, cb);
48 | },
49 | use: function use(cb) {
50 | var client = _client.Client.getInstance();
51 | client.middleware.push(cb);
52 | }
53 | };
54 |
55 | Scorocode.Query = _query.SCQuery;
56 | Scorocode.Object = _object.SCObject;
57 | Scorocode.User = _user.SCUser;
58 | Scorocode.UpdateOps = _updateOps.SCUpdateOps;
59 | Scorocode.Messenger = _messenger.SCMessenger;
60 | Scorocode.CloudCode = _cloudCode.SCCloudCode;
61 | Scorocode.WebSocket = _websocket.SCWebSocket;
62 | Scorocode.System = _system.SCSystem;
63 | Scorocode.Logger = _logger.SCLogger;
64 | Scorocode.Bot = _bot.SCBot;
65 | Scorocode.Instance = _instance.SCInstance;
66 | Scorocode.Field = _system.SCField;
67 |
68 | module.exports = Scorocode;
--------------------------------------------------------------------------------
/dist/websocket.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCWebSocket = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _client = require('./client');
11 |
12 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13 |
14 | var SCWebSocket = exports.SCWebSocket = function () {
15 | function SCWebSocket(chanName) {
16 | var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
17 |
18 | _classCallCheck(this, SCWebSocket);
19 |
20 | var self = this;
21 |
22 | if (!chanName) {
23 | throw new Error('Channel name is empty');
24 | }
25 |
26 | var cl = _client.Client.getInstance();
27 | var ws = cl.isNode ? require('ws') : WebSocket;
28 |
29 | var AppId = cl.applicationID;
30 | var wsKey = cl.websocketKey;
31 | var host = cl.get('WSHOST');
32 | var protocol = cl.get('WS_PROTOCOL');
33 |
34 | this.wsInstanse = new ws(protocol + '://' + host + '/' + AppId + '/' + wsKey + '/' + chanName);
35 | this._handlers = {};
36 |
37 | this.wsInstanse.onclose = function (event) {
38 | self._emit('close', {
39 | wasClean: event.wasClean,
40 | code: event.code,
41 | reason: event.reason
42 | });
43 | };
44 | this.wsInstanse.onerror = function (error) {
45 | self._emit('error', error);
46 | };
47 | this.wsInstanse.onmessage = function (event) {
48 | self._emit('message', event.data);
49 | };
50 | this.wsInstanse.onopen = function () {
51 | self._emit('open');
52 | };
53 | }
54 |
55 | _createClass(SCWebSocket, [{
56 | key: '_emit',
57 | value: function _emit() {
58 |
59 | var args = [];
60 | for (var i = 0; i < arguments.length; i++) {
61 | args[i] = arguments[i];
62 | }
63 |
64 | var ev = args.shift();
65 |
66 | if (!this._handlers[ev]) {
67 | this._handlers[ev] = [];
68 | }
69 |
70 | var ln = this._handlers[ev].length;
71 |
72 | for (var _i = 0; _i < ln; _i++) {
73 | this._handlers[ev][_i].apply(null, args);
74 | }
75 | }
76 | }, {
77 | key: 'on',
78 | value: function on(ev, cb) {
79 | if (!this._handlers[ev]) {
80 | this._handlers[ev] = [];
81 | }
82 |
83 | this._handlers[ev].push(cb);
84 | }
85 | }, {
86 | key: 'send',
87 | value: function send(msg) {
88 | this.wsInstanse.send(msg);
89 | }
90 | }]);
91 |
92 | return SCWebSocket;
93 | }();
--------------------------------------------------------------------------------
/src/messenger.js:
--------------------------------------------------------------------------------
1 | import {SCQuery} from './query'
2 | import {MessengerProtocol} from './protocol'
3 | import {Utils} from './utils'
4 | import {HttpRequest} from './httpRequest'
5 | import {SDKOptions} from './client'
6 | import {SCWebSocket} from './websocket'
7 | import {SCLogger} from './logger'
8 |
9 | export class SCMessenger {
10 | constructor(opt = {}) {
11 | if (opt.logger instanceof SCLogger) {
12 | this.logger = opt.logger;
13 | this._ws = new SCWebSocket("messenger_debugger");
14 | this._ws.on("open", () => {
15 | this.logger.log('Debugger is active');
16 | });
17 | this._ws.on("error", (err) => {
18 | this.logger.error(err);
19 | });
20 | this._ws.on("message", (msg) => {
21 | this.logger.log(msg);
22 | });
23 | }
24 | }
25 |
26 | sendPush (options, debug, callbacks = {}) {
27 | if (typeof options !== 'object') {
28 | throw new Error('Invalid options type');
29 | }
30 |
31 | if (!(options.where instanceof SCQuery)) {
32 | throw new Error('Where must be a type of Query');
33 | }
34 |
35 | if (typeof options.data !== 'object') {
36 | throw new Error('Invalid data type');
37 | }
38 |
39 | if (typeof debug === 'object') {
40 | callbacks = debug
41 | }
42 |
43 | let protocolOpts = {
44 | url: SDKOptions.SEND_PUSH_URL
45 | };
46 |
47 | let data = {
48 | msg: options.data,
49 | debug: debug
50 | };
51 |
52 | Utils.extend(data, options.where.toJson());
53 |
54 | const protocol = MessengerProtocol.init(data, protocolOpts);
55 | const request = new HttpRequest(protocol);
56 | const promise = request.execute()
57 | .then(data => {
58 | return JSON.parse(data);
59 | })
60 | .then(response => {
61 | if (response.error) {
62 | return Promise.reject(response);
63 | }
64 |
65 | return response;
66 | });
67 |
68 | return Utils.wrapCallbacks(promise, callbacks);
69 | }
70 | sendSms (options, debug, callbacks = {}) {
71 | if (typeof options !== 'object') {
72 | throw new Error('Invalid options type');
73 | }
74 |
75 | if (!(options.where instanceof SCQuery)) {
76 | throw new Error('Where must be a type of Query');
77 | }
78 |
79 | if (typeof options.data !== 'object') {
80 | throw new Error('Invalid data type');
81 | }
82 |
83 | if (typeof options.data.text !== 'string') {
84 | throw new Error('Missing subject or text message');
85 | }
86 |
87 | if (typeof debug === 'object') {
88 | callbacks = debug
89 | }
90 |
91 | let protocolOpts = {
92 | url: SDKOptions.SEND_SMS_URL
93 | };
94 |
95 | let data = {
96 | msg: options.data,
97 | debug: debug
98 | };
99 |
100 | Utils.extend(data, options.where.toJson());
101 |
102 | const protocol = MessengerProtocol.init(data, protocolOpts);
103 | const request = new HttpRequest(protocol);
104 | const promise = request.execute()
105 | .then(data => {
106 | return JSON.parse(data);
107 | })
108 | .then(response => {
109 | if (response.error) {
110 | return Promise.reject(response);
111 | }
112 |
113 | return response;
114 | });
115 |
116 | return Utils.wrapCallbacks(promise, callbacks);
117 | }
118 | }
--------------------------------------------------------------------------------
/src/user.js:
--------------------------------------------------------------------------------
1 | import {UserProtocol} from './protocol'
2 | import {HttpRequest} from './httpRequest'
3 | import {Utils} from './utils'
4 | import {Client, SDKOptions} from './client'
5 | import {SCObject} from './object';
6 |
7 | export class SCUser extends SCObject{
8 | constructor(user) {
9 | super('users', user);
10 | }
11 |
12 | signup(options = {}) {
13 | let protocolOpts = {
14 | url: SDKOptions.SIGN_UP_URL
15 | };
16 |
17 | let data = {
18 | username: this.attrs.username,
19 | email: this.attrs.email,
20 | password: this.attrs.password
21 | };
22 | const protocol = UserProtocol.init(data, this.attrs, protocolOpts);
23 | const request = new HttpRequest(protocol);
24 | const promise = request.execute()
25 | .then(response => {
26 | return JSON.parse(response);
27 | })
28 | .then(response => {
29 | if (response.error) {
30 | return Promise.reject(response);
31 | }
32 |
33 | Utils.extend(this.attrs, response.result);
34 |
35 | return response.result;
36 | });
37 | return Utils.wrapCallbacks(promise, options);
38 | }
39 |
40 | logout(options = {}) {
41 | let protocolOpts = {
42 | url: SDKOptions.LOGOUT_URL
43 | };
44 |
45 | const protocol = UserProtocol.init(null, null, protocolOpts);
46 | const request = new HttpRequest(protocol);
47 | const promise = request.execute()
48 | .then(response => {
49 | return JSON.parse(response);
50 | })
51 | .then(response => {
52 | if (!response.error) {
53 | const client = Client.getInstance();
54 | client.sessionId = "";
55 | }
56 |
57 | return response;
58 | });
59 | return Utils.wrapCallbacks(promise, options);
60 | }
61 |
62 | authorize(options = {}) {
63 | let protocolOpts = {
64 | url: SDKOptions.GET_AUTH_URL
65 | };
66 |
67 | const protocol = UserProtocol.init(null, null, protocolOpts);
68 | const request = new HttpRequest(protocol);
69 | const promise = request.execute()
70 | .then(data => {
71 | return JSON.parse(data);
72 | })
73 | .then(response => {
74 | if (response.error) {
75 | return Promise.reject(response);
76 | }
77 |
78 | const client = Client.getInstance();
79 | client.sessionId = response.result.sessionId;
80 |
81 | Utils.extend(this.attrs, response.result.user);
82 |
83 | return response.result.user;
84 | });
85 | return Utils.wrapCallbacks(promise, options);
86 | }
87 |
88 | login(email, password, options = {}) {
89 | let protocolOpts = {
90 | url: SDKOptions.LOGIN_URL
91 | };
92 |
93 | const protocol = UserProtocol.init({email:email, password: password}, null, protocolOpts);
94 | const request = new HttpRequest(protocol);
95 | const promise = request.execute()
96 | .then(data => {
97 | return JSON.parse(data);
98 | })
99 | .then(response => {
100 | if (response.error) {
101 | return Promise.reject(response);
102 | }
103 |
104 | const client = Client.getInstance();
105 | client.sessionId = response.result.sessionId;
106 |
107 | Utils.extend(this.attrs, response.result.user);
108 |
109 | return response.result.user;
110 | });
111 |
112 | return Utils.wrapCallbacks(promise, options);
113 | }
114 | }
--------------------------------------------------------------------------------
/src/cloudCode.js:
--------------------------------------------------------------------------------
1 | import {CloudCodeProtocol} from './protocol'
2 | import {Utils} from './utils'
3 | import {HttpRequest} from './httpRequest'
4 | import {SDKOptions} from './client'
5 | import {SCWebSocket} from './websocket'
6 | import {SCLogger} from './logger'
7 |
8 | export class SCCloudCode {
9 | constructor(id, opt = {}) {
10 | if (typeof id !== 'string') {
11 | throw new Error('Invalid script id');
12 | }
13 | this.debugChannel = ('0' + Math.random()*10000000).slice(-7);
14 |
15 | if (opt.logger instanceof SCLogger) {
16 | this.logger = opt.logger;
17 | this._ws = new SCWebSocket(this.debugChannel);
18 | this._ws.on("open", () => {});
19 | this._ws.on("error", (err) => {
20 | this.logger.error(err);
21 | });
22 | this._ws.on("message", (msg) => {
23 | this.logger.log(msg);
24 | });
25 | }
26 |
27 | this.isRunByPath = !!opt.isRunByPath;
28 | this.id = id;
29 |
30 |
31 | }
32 |
33 | runSync(pool = {}, callbacks) {
34 | if (typeof pool !== 'object') {
35 | throw new Error('Invalid type of pool');
36 | }
37 |
38 | let protocolOpts = {
39 | url: SDKOptions.CLOUD_CODE_URL
40 | };
41 |
42 | const channelId = parseInt(Math.random() * 10000000);
43 |
44 | const protocol = CloudCodeProtocol.init({
45 | script: this.isRunByPath ? "" : this.id,
46 | isRunByPath: this.isRunByPath,
47 | path: this.isRunByPath ? this.id : "",
48 | pool: Object.assign({channelId: channelId}, pool),
49 | debug: false
50 | }, protocolOpts);
51 |
52 | const promise = new Promise((resolve, reject) => {
53 | const request = new HttpRequest(protocol);
54 | var ws = new SCWebSocket(channelId);
55 |
56 | const timeout = setTimeout(() => {
57 | ws.wsInstanse.close();
58 | clearTimeout(timeout);
59 | reject({errMsg: 'Gateway Timeout', errCode: 504, error: true});
60 | }, 120000);
61 |
62 | ws.on("open", () => {
63 | request.execute()
64 | .then(data => {
65 | return JSON.parse(data);
66 | })
67 | .then(response => {
68 | if (response.error) {
69 | return reject(response);
70 | }
71 | });
72 | });
73 | ws.on("error", (err) => {
74 | return reject(err);
75 | });
76 | ws.on("message", (msg) => {
77 | ws.wsInstanse.close();
78 | clearTimeout(timeout);
79 | return resolve(msg);
80 | });
81 |
82 | });
83 |
84 | return Utils.wrapCallbacks(promise, callbacks);
85 | }
86 |
87 | run(pool = {}, debug, callbacks) {
88 | if (typeof pool !== 'object') {
89 | throw new Error('Invalid type of pool');
90 | }
91 |
92 | if (typeof debug === 'object') {
93 | callbacks = debug
94 | }
95 |
96 | let protocolOpts = {
97 | url: SDKOptions.CLOUD_CODE_URL
98 | };
99 |
100 | const protocol = CloudCodeProtocol.init({
101 | isRunByPath: this.isRunByPath,
102 | script: this.isRunByPath ? "" : this.id,
103 | path: this.isRunByPath ? this.id : "",
104 | pool: pool,
105 | debug: debug,
106 | debugChannel: this.debugChannel
107 | }, protocolOpts);
108 |
109 |
110 | const request = new HttpRequest(protocol);
111 | const promise = request.execute()
112 | .then(data => {
113 | return JSON.parse(data);
114 | })
115 | .then(response => {
116 | if (response.error) {
117 | return Promise.reject(response);
118 | }
119 |
120 | return response;
121 | });
122 |
123 | return Utils.wrapCallbacks(promise, callbacks);
124 | }
125 | }
--------------------------------------------------------------------------------
/src/client.js:
--------------------------------------------------------------------------------
1 | let sharedInstance;
2 | export const SDKOptions = {
3 | WSHOST: 'wss.scorocode.ru',
4 | WS_PROTOCOL: 'wss',
5 | HOST: 'api.scorocode.ru',
6 | PORT: '443',
7 |
8 | CREATE_INSTANCE_URL: '/api/v1/instance/create',
9 | UPDATE_INSTANCE_URL: '/api/v1/instance/update',
10 | REMOVE_INSTANCE_URL: '/api/v1/instance/delete',
11 | RUN_INSTANCE_URL: '/api/v1/instance/run',
12 | STOP_INSTANCE_URL: '/api/v1/instance/stop',
13 | LIST_INSTANCE_URL: '/api/v1/instance',
14 | SCRIPTS_INSTANCE_URL: '/api/v1/instance/scripts',
15 | RUN_SCRIPT_INSTANCE_URL: '/api/v1/instance/scripts/run',
16 | KILL_SCRIPT_INSTANCE_URL: '/api/v1/instance/scripts/delete',
17 |
18 | GET_AUTH_URL: '/api/v1/verifylogin',
19 |
20 | FIND_URL: '/api/v1/data/find',
21 | COUNT_URL: '/api/v1/data/count',
22 | UPDATE_URL: '/api/v1/data/update',
23 | UPDATE_BY_ID_URL: '/api/v1/data/updatebyid',
24 | REMOVE_URL: '/api/v1/data/remove',
25 | INSERT_URL: '/api/v1/data/insert',
26 |
27 | SEND_PUSH_URL: '/api/v1/sendpush',
28 | SEND_SMS_URL: '/api/v1/sendsms',
29 |
30 | CLOUD_CODE_URL: '/api/v1/scripts',
31 |
32 | UPLOAD_URL: '/api/v1/upload',
33 | REMOVE_FILE_URL: '/api/v1/deletefile',
34 | GET_FILE_LINK_URL: '',
35 |
36 | SIGN_UP_URL: '/api/v1/register',
37 | LOGOUT_URL: '/api/v1/logout',
38 | LOGIN_URL: '/api/v1/login',
39 |
40 | DATA_STATS: '/api/v1/stat',
41 |
42 | BOT_HOST: 'bots.scorocode.ru',
43 | BOT_URL: '/bots/',
44 |
45 | /* Работа с приложением */
46 | GET_APP_URL: '/api/v1/app',
47 | UPDATE_APP_KEY: '/api/v1/app/keys/update',
48 | GET_COLLECTIONS_URL: '/api/v1/app/collections',
49 | GET_COLLECTION_URL: '/api/v1/app/collections/get',
50 | CREATE_COLLECTION_URL: '/api/v1/app/collections/create',
51 | UPDATE_COLLECTION_URL: '/api/v1/app/collections/update',
52 | DELETE_COLLECTION_URL: '/api/v1/app/collections/delete',
53 | CLONE_COLLECTION_URL: '/api/v1/app/collections/clone',
54 | CREATE_INDEX_URL: '/api/v1/app/collections/index/create',
55 | DELETE_INDEX_URL: '/api/v1/app/collections/index/delete',
56 | CREATE_FIELD_URL: '/api/v1/app/collections/fields/create',
57 | UPDATE_FIELD_URL: '/api/v1/app/collections/fields/update',
58 | DELETE_FIELD_URL: '/api/v1/app/collections/fields/delete',
59 | UPDATE_TRIGGERS_URL: '/api/v1/app/collections/triggers',
60 | GET_FOLDERS_URL: '/api/v1/app/scripts/folders',
61 | CREATE_FOLDER_URL: '/api/v1/app/scripts/folders/create',
62 | DELETE_FOLDER_URL: '/api/v1/app/scripts/folders/delete',
63 | GET_SCRIPT_URL: '/api/v1/app/scripts/get',
64 | CREATE_SCRIPT_URL: '/api/v1/app/scripts/create',
65 | UPDATE_SCRIPT_URL: '/api/v1/app/scripts/update',
66 | DELETE_SCRIPT_URL: '/api/v1/app/scripts/delete',
67 | GET_BOTS_URL: '/api/v1/bots',
68 | CREATE_BOT_URL: '/api/v1/bots/create',
69 | UPDATE_BOT_URL: '/api/v1/bots/update',
70 | DELETE_BOT_URL: '/api/v1/bots/delete',
71 | TIMEOUT: 120000
72 |
73 | };
74 | export class Client {
75 | constructor(options) {
76 | if (typeof options.ApplicationID !== 'string') {
77 | throw new Error('Invalid Application ID');
78 | }
79 |
80 | if (typeof options.JavaScriptKey !== 'string') {
81 | throw new Error('Invalid JavaScript Key');
82 | }
83 |
84 | if (options.MasterKey && typeof options.MasterKey !== 'string') {
85 | throw new Error('Invalid MasterKey');
86 | }
87 |
88 | this.middleware = [];
89 |
90 | this.applicationID = options.ApplicationID;
91 | this.clientKey = options.JavaScriptKey;
92 | this.masterKey = options.MasterKey || "";
93 | this.messageKey = options.MessageKey || "";
94 | this.scriptKey = options.ScriptKey || "";
95 | this.fileKey = options.FileKey || "";
96 | this.websocketKey = options.WebSocketKey || "";
97 | this.sessionId = options.sessionId || "";
98 |
99 | this.host = "https://scorocode.ru";
100 | this.port = "443";
101 |
102 | /* Not implemented yet */
103 | if (options.EncryptKey && typeof options.EncryptKey !== 'string') {
104 | throw new Error('Invalid EncryptKey');
105 | }
106 | this.EncryptKey = '';
107 | this.isNode = false;
108 |
109 | if (typeof process === 'object' && process + '' === '[object process]') {
110 | this.isNode = true;
111 | }
112 | }
113 |
114 | get(key) {
115 | return SDKOptions[key];
116 | }
117 |
118 | set(key, value) {
119 | SDKOptions[key] = value;
120 | }
121 |
122 | static init(options) {
123 | const client = new Client(options);
124 | sharedInstance = client;
125 | return client;
126 | }
127 |
128 | static getInstance() {
129 | return sharedInstance;
130 | }
131 |
132 | }
--------------------------------------------------------------------------------
/src/httpRequest.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | import SCObserver from './observer'
3 | import {Client} from './client'
4 |
5 | var https = null;
6 | if (typeof XMLHttpRequest === 'undefined') {
7 | https = require('https');
8 | }
9 |
10 | export class HttpRequest {
11 | constructor(options) {
12 | this.method = "";
13 | this.port = "";
14 | this.path = "";
15 | this.host = "";
16 | this.data = "";
17 | this.headers = {};
18 |
19 | let protocolJson = options.toJson();
20 |
21 | for (let prop in protocolJson) {
22 | this[prop] = protocolJson[prop];
23 | }
24 | }
25 |
26 | node_request() {
27 | const promise = new Promise((resolve, reject) => {
28 | const request = https.request({
29 | method: this.method,
30 | port: this.port,
31 | path: this.path,
32 | host: this.host,
33 | headers: this.headers
34 | }, function(res) {
35 | let result = "";
36 | if (res.statusCode !== 200) {
37 | return reject({
38 | error : true,
39 | errCode : res.statusCode,
40 | errMsg : res.responseText || 'Invalid statusCode'
41 | });
42 | }
43 |
44 | res.on('data', function(data) {
45 | result += data.toString();
46 | });
47 |
48 | res.on('error', function(err) {
49 | return reject({
50 | error : true,
51 | errCode : res.statusCode,
52 | errMsg : err.message
53 | });
54 | });
55 |
56 | res.on('end', function(){
57 | return resolve(result);
58 | })
59 | });
60 |
61 | request.on('aborted', function () {
62 | return reject({
63 | error : true,
64 | errCode : 504,
65 | errMsg : 'Request has been aborted by the server'
66 | });
67 | });
68 |
69 | request.on('abort', function () {
70 | return reject({
71 | error : true,
72 | errCode : 418,
73 | errMsg : 'Request has been aborted by the client'
74 | });
75 | });
76 |
77 | request.on('error', function (err) {
78 | return reject({
79 | error : true,
80 | errCode : 422,
81 | errMsg : err.message
82 | });
83 | });
84 |
85 | request.setTimeout(this.timeout, function(){
86 | request.abort();
87 | });
88 |
89 | request.write(this.data);
90 | request.end();
91 | });
92 | return promise;
93 |
94 | }
95 | ajax(options = {}) {
96 | const promise = new Promise((resolve, reject) => {
97 | let url = 'https://' + this.host + this.path;
98 | var xhr = new XMLHttpRequest();
99 |
100 | xhr.timeout = this.timeout;
101 | xhr.open(this.method, url, true);
102 |
103 | for (var prop in this.headers) {
104 | xhr.setRequestHeader(prop, this.headers[prop]);
105 | }
106 |
107 | xhr.onreadystatechange = () => {
108 | if (xhr.readyState != 4) return;
109 | if (xhr.status != 200) {
110 | return reject(new Error('Invalid statusCode: ' + xhr.status));
111 | } else {
112 | resolve(xhr.responseText)
113 | }
114 | };
115 | options.onXHRPrepare && options.onXHRPrepare(xhr);
116 | xhr.send(this.data)
117 | });
118 |
119 | return promise;
120 | }
121 | request(options = {}) {
122 | if (typeof XMLHttpRequest !== 'undefined') {
123 | return this.ajax(options);
124 | }
125 | return this.node_request();
126 | }
127 |
128 | execute(options = {}) {
129 | const client = Client.getInstance();
130 |
131 | var wrap = (fn) => () => fn()
132 | .then(data => {
133 | return JSON.parse(data);
134 | })
135 | .then(res => {
136 | if (res.error) {
137 | return Promise.reject(res);
138 | }
139 |
140 | return Promise.resolve(JSON.stringify(res));
141 | })
142 | .catch(err => {
143 | SCObserver().emit('error', err);
144 | return Promise.reject(err);
145 | });
146 |
147 | var fn = wrap(this.request.bind(this));
148 |
149 | for (var i = 0; i < client.middleware.length; i++) {
150 | fn = client.middleware[i](fn)
151 | }
152 |
153 | return fn(options);
154 |
155 | }
156 | }
--------------------------------------------------------------------------------
/src/object.js:
--------------------------------------------------------------------------------
1 | import {SCQuery} from "./query"
2 | import {Utils} from "./utils"
3 | import {operators} from "./updateOps"
4 | import {DataStore} from "./stores/data"
5 | import {Client} from './client'
6 |
7 | export class SCObject {
8 | constructor(collName, model) {
9 | if (typeof collName !== 'string') {
10 | throw new Error('Invalid collection name');
11 | }
12 |
13 | this.collection = collName;
14 | this.attrs = Object.assign({}, model);
15 | this.update = {};
16 |
17 | for (let prop in operators) {
18 | this[prop] = operators[prop];
19 | }
20 | }
21 |
22 | setAttrs (obj) {
23 | const model = Object.assign({}, obj);
24 | for (let item in model) {
25 | this.set(item, model[item]);
26 | }
27 | }
28 |
29 | getAttrs () {
30 | return Object.assign({}, this.attrs);
31 | }
32 |
33 | getById(id, options) {
34 | let query = new SCQuery(this.collection);
35 |
36 | if (!id) {
37 | throw new Error('Id is empty');
38 | }
39 |
40 | const promise = query.equalTo('_id',id).find(options).then(data => {
41 | if (!data.result.length) {
42 | throw new Error('Document not found');
43 | }
44 |
45 | this.attrs = {};
46 | Utils.extend(this.attrs, data.result[0]);
47 |
48 | return data.result[0];
49 | });
50 |
51 | return promise;
52 | }
53 |
54 | get(key) {
55 | return this.attrs[key];
56 | }
57 |
58 | getFileLink(field) {
59 | if (!this.attrs['_id']) {
60 | throw new Error('You must first create a document and upload file');
61 | }
62 |
63 | if (!this.attrs.hasOwnProperty(field)) {
64 | throw new Error('Unknown field');
65 | }
66 |
67 | if (!this.attrs[field]) {
68 | throw new Error('Field is empty');
69 | }
70 |
71 | const client = Client.getInstance();
72 | return 'https://api.scorocode.ru/api/v1/getfile/' + client.applicationID + '/' + this.collection + '/' + field + '/' + this.attrs._id + '/' + this.attrs[field];
73 | }
74 |
75 | removeFile(field, options = {}) {
76 | if (!this.attrs['_id']) {
77 | throw new Error('You must first create a document and upload file');
78 | }
79 |
80 | if (!this.attrs.hasOwnProperty(field)) {
81 | throw new Error('Unknown field');
82 | }
83 |
84 | if (!this.attrs[field]) {
85 | throw new Error('Field is empty');
86 | }
87 |
88 | let QueryJSON = this.toJson();
89 | let params = {
90 | coll: QueryJSON.coll,
91 | docId: this.attrs['_id'],
92 | field: field,
93 | file: this.attrs[field]
94 | };
95 | return DataStore.getInstance().removeFile(params, options).then(data => {
96 | if (!data.error) {
97 | this.attrs[field] = '';
98 | }
99 | return data;
100 | });
101 | }
102 |
103 | uploadFile(field, filename, file, options = {}) {
104 | if (!this.attrs['_id']) {
105 | throw new Error('You must first create a document');
106 | }
107 |
108 | var base64 = file.split(',');
109 | var base64result = "";
110 |
111 | if (base64.length == 2) {
112 | base64result = base64[1];
113 | } else {
114 | base64result = base64[0];
115 | }
116 |
117 | let QueryJSON = this.toJson();
118 |
119 | let params = {
120 | coll: QueryJSON.coll,
121 | docId: this.attrs['_id'],
122 | field: field,
123 | file: filename,
124 | content: base64result
125 | };
126 | return DataStore.getInstance().uploadFile(params, options).then(data => {
127 |
128 | if (!data.error) {
129 | this.attrs[field] = data.result;
130 | }
131 | return data;
132 | });
133 | }
134 |
135 | toJson() {
136 | const json = {
137 | coll: this.collection,
138 | query: this.attrs['_id'] ? { _id: this.attrs['_id']} : {},
139 | doc: this.attrs['_id'] ? this.update : this.attrs
140 | };
141 | return json;
142 | }
143 |
144 | save(options = {}) {
145 | if (this.attrs['_id']) {
146 | return DataStore.getInstance().updateById(this.toJson(), options).then(data => {
147 | if (!data.error) {
148 | this.attrs = data.result;
149 | }
150 | this.update = {};
151 | return data.result;
152 | });
153 | }
154 |
155 | return DataStore.getInstance().insert(this.toJson(), options).then(data => {
156 | if (!data.error) {
157 | this.attrs = data.result;
158 | }
159 | return data.result;
160 | });
161 | }
162 |
163 | remove(options = {}) {
164 | if (!this.attrs['_id']) {
165 | throw new Error("Document does't exist");
166 | }
167 | let query = new SCQuery(this.collection);
168 | return query.equalTo('_id',this.attrs._id).remove(options).then(data => {
169 | return data;
170 | });
171 | }
172 |
173 | static extend(collName, childObject) {
174 | const obj = new SCObject(collName);
175 | for (let prop in childObject) {
176 | obj.attrs[prop] = childObject[prop];
177 | }
178 |
179 | return obj;
180 | }
181 |
182 | }
--------------------------------------------------------------------------------
/src/protocol.js:
--------------------------------------------------------------------------------
1 | import {Client} from './client'
2 |
3 | export class Protocol {
4 | constructor(client, opts) {
5 | this.method = 'POST';
6 | this.host = client.get('HOST');
7 | this.port = client.get('PORT');
8 | this.path = opts.url;
9 | this.data = {
10 | app: client.applicationID,
11 | cli: client.clientKey,
12 | acc: client.masterKey,
13 | //sess: client.sessionId
14 | };
15 | this.headers = {
16 | 'Content-Type': 'application/json'
17 | };
18 |
19 | if (client.sessionId) {
20 | this.headers['Authorization'] = 'Bearer ' + client.sessionId;
21 | }
22 |
23 | this.timeout = opts.timeout || client.get('TIMEOUT');
24 | }
25 |
26 | static init(opts) {
27 | const client = Client.getInstance();
28 | const protocol = new Protocol(client, opts);
29 |
30 | return protocol;
31 | }
32 | setAccessKey(key, value) {
33 | this.data[key] = value;
34 | return this;
35 | }
36 |
37 | setData(data) {
38 | for (var prop in data) {
39 | Object.defineProperty(this.data, prop, {
40 | value: data[prop],
41 | enumerable: true,
42 | writable: true,
43 | configurable: true
44 | })
45 | }
46 |
47 | return this;
48 | }
49 |
50 | setDoc(doc) {
51 | if (doc) {
52 | this.data.doc = doc;
53 | }
54 |
55 | return this;
56 | }
57 |
58 | setIndex(index) {
59 | this.data.index = index;
60 | }
61 |
62 | setField(field) {
63 | this.data.collField = field;
64 | }
65 |
66 | setPath(path) {
67 | this.data.path = path;
68 | }
69 |
70 | setTriggers(triggers) {
71 | this.data.triggers = triggers;
72 | }
73 |
74 | setColl(coll) {
75 | this.data.coll = coll;
76 |
77 | return this;
78 | }
79 |
80 | setCollection(coll) {
81 | this.data.collection = coll;
82 |
83 | return this;
84 | }
85 |
86 | toJson() {
87 | const Json = {};
88 |
89 | for (let prop in this) {
90 | if (prop === 'data') {
91 | Json[prop] = JSON.stringify(this[prop]);
92 | continue;
93 | }
94 | Json[prop] = this[prop];
95 | }
96 |
97 | return Json;
98 | }
99 | }
100 |
101 | export class DataProtocol extends Protocol {
102 | constructor(client, opts) {
103 | super(client, opts);
104 | }
105 |
106 | static init(query = {}, doc = {}, opts) {
107 | const client = Client.getInstance();
108 | const protocol = new DataProtocol(client, opts);
109 | protocol.setData(query);
110 | protocol.setDoc(doc);
111 |
112 | return protocol;
113 | }
114 | }
115 |
116 | export class UserProtocol extends Protocol {
117 | constructor(client, opts) {
118 | super(client, opts);
119 | }
120 |
121 | static init(data, doc, opts) {
122 | const client = Client.getInstance();
123 | const protocol = new UserProtocol(client, opts);
124 | protocol.setData(data);
125 | protocol.setDoc(doc);
126 |
127 | return protocol;
128 | }
129 | }
130 |
131 | export class MessengerProtocol extends Protocol {
132 | constructor(client, options) {
133 | super(client, options);
134 | }
135 |
136 | static init(data, options) {
137 | const client = Client.getInstance();
138 | const protocol = new MessengerProtocol(client, options);
139 | protocol.setData(data);
140 | protocol.setAccessKey('acc', client.masterKey || client.messageKey);
141 | return protocol;
142 | }
143 | }
144 |
145 | export class CloudCodeProtocol extends Protocol {
146 | constructor(client, options) {
147 | super(client, options);
148 | }
149 |
150 | static init(data, options) {
151 | const client = Client.getInstance();
152 | const protocol = new CloudCodeProtocol(client, options);
153 | protocol.setData(data);
154 | protocol.setAccessKey('acc', client.masterKey || client.scriptKey);
155 | return protocol;
156 | }
157 | }
158 |
159 | export class BotProtocol {
160 | constructor(botId, client, opts) {
161 | this.method = 'POST';
162 | this.host = client.get('BOT_HOST');
163 | this.port = client.get('PORT');
164 | this.path = client.get('BOT_URL') + botId + '/response';
165 | this.data = {};
166 | this.headers = {
167 | 'Content-Type': 'application/json'
168 | };
169 | this.timeout = opts.timeout || client.get('TIMEOUT');
170 | }
171 |
172 | static init(botId, options = {}) {
173 | const client = Client.getInstance();
174 | const protocol = new BotProtocol(botId, client, options);
175 |
176 | return protocol;
177 | }
178 |
179 | setData(data) {
180 | for (var prop in data) {
181 | Object.defineProperty(this.data, prop, {
182 | value: data[prop],
183 | enumerable: true,
184 | writable: true,
185 | configurable: true
186 | })
187 | }
188 | }
189 |
190 | toJson() {
191 | const Json = {};
192 |
193 | for (let prop in this) {
194 | if (prop === 'data') {
195 | Json[prop] = JSON.stringify(this[prop]);
196 | continue;
197 | }
198 | Json[prop] = this[prop];
199 | }
200 |
201 | return Json;
202 | }
203 | }
204 |
205 | export class CloudFileProtocol extends Protocol {
206 | constructor() {
207 | super();
208 | this.docId = "";
209 | this.field = "";
210 | }
211 | }
--------------------------------------------------------------------------------
/dist/messenger.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCMessenger = undefined;
7 |
8 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
9 |
10 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
11 |
12 | var _query = require('./query');
13 |
14 | var _protocol = require('./protocol');
15 |
16 | var _utils = require('./utils');
17 |
18 | var _httpRequest = require('./httpRequest');
19 |
20 | var _client = require('./client');
21 |
22 | var _websocket = require('./websocket');
23 |
24 | var _logger = require('./logger');
25 |
26 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
27 |
28 | var SCMessenger = exports.SCMessenger = function () {
29 | function SCMessenger() {
30 | var _this = this;
31 |
32 | var opt = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
33 |
34 | _classCallCheck(this, SCMessenger);
35 |
36 | if (opt.logger instanceof _logger.SCLogger) {
37 | this.logger = opt.logger;
38 | this._ws = new _websocket.SCWebSocket("messenger_debugger");
39 | this._ws.on("open", function () {
40 | _this.logger.log('Debugger is active');
41 | });
42 | this._ws.on("error", function (err) {
43 | _this.logger.error(err);
44 | });
45 | this._ws.on("message", function (msg) {
46 | _this.logger.log(msg);
47 | });
48 | }
49 | }
50 |
51 | _createClass(SCMessenger, [{
52 | key: 'sendPush',
53 | value: function sendPush(options, debug) {
54 | var callbacks = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
55 |
56 | if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
57 | throw new Error('Invalid options type');
58 | }
59 |
60 | if (!(options.where instanceof _query.SCQuery)) {
61 | throw new Error('Where must be a type of Query');
62 | }
63 |
64 | if (_typeof(options.data) !== 'object') {
65 | throw new Error('Invalid data type');
66 | }
67 |
68 | if ((typeof debug === 'undefined' ? 'undefined' : _typeof(debug)) === 'object') {
69 | callbacks = debug;
70 | }
71 |
72 | var protocolOpts = {
73 | url: _client.SDKOptions.SEND_PUSH_URL
74 | };
75 |
76 | var data = {
77 | msg: options.data,
78 | debug: debug
79 | };
80 |
81 | _utils.Utils.extend(data, options.where.toJson());
82 |
83 | var protocol = _protocol.MessengerProtocol.init(data, protocolOpts);
84 | var request = new _httpRequest.HttpRequest(protocol);
85 | var promise = request.execute().then(function (data) {
86 | return JSON.parse(data);
87 | }).then(function (response) {
88 | if (response.error) {
89 | return Promise.reject(response);
90 | }
91 |
92 | return response;
93 | });
94 |
95 | return _utils.Utils.wrapCallbacks(promise, callbacks);
96 | }
97 | }, {
98 | key: 'sendSms',
99 | value: function sendSms(options, debug) {
100 | var callbacks = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
101 |
102 | if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
103 | throw new Error('Invalid options type');
104 | }
105 |
106 | if (!(options.where instanceof _query.SCQuery)) {
107 | throw new Error('Where must be a type of Query');
108 | }
109 |
110 | if (_typeof(options.data) !== 'object') {
111 | throw new Error('Invalid data type');
112 | }
113 |
114 | if (typeof options.data.text !== 'string') {
115 | throw new Error('Missing subject or text message');
116 | }
117 |
118 | if ((typeof debug === 'undefined' ? 'undefined' : _typeof(debug)) === 'object') {
119 | callbacks = debug;
120 | }
121 |
122 | var protocolOpts = {
123 | url: _client.SDKOptions.SEND_SMS_URL
124 | };
125 |
126 | var data = {
127 | msg: options.data,
128 | debug: debug
129 | };
130 |
131 | _utils.Utils.extend(data, options.where.toJson());
132 |
133 | var protocol = _protocol.MessengerProtocol.init(data, protocolOpts);
134 | var request = new _httpRequest.HttpRequest(protocol);
135 | var promise = request.execute().then(function (data) {
136 | return JSON.parse(data);
137 | }).then(function (response) {
138 | if (response.error) {
139 | return Promise.reject(response);
140 | }
141 |
142 | return response;
143 | });
144 |
145 | return _utils.Utils.wrapCallbacks(promise, callbacks);
146 | }
147 | }]);
148 |
149 | return SCMessenger;
150 | }();
--------------------------------------------------------------------------------
/src/instance.js:
--------------------------------------------------------------------------------
1 | import {Utils} from './utils'
2 | import {HttpRequest} from './httpRequest'
3 | import {Protocol} from './protocol'
4 | import {SDKOptions} from './client'
5 |
6 | export class SCInstance {
7 | constructor(data) {
8 | this._extend(data);
9 | }
10 |
11 | _extend(data) {
12 | for (let it in data) {
13 | this[it] = data[it];
14 | }
15 | }
16 |
17 | save(callbacks = {}) {
18 | let protocolOpts = !this.id ? {
19 | url: SDKOptions.CREATE_INSTANCE_URL
20 | } : {
21 | url: SDKOptions.UPDATE_INSTANCE_URL
22 | };
23 |
24 |
25 | const protocol = Protocol.init(protocolOpts);
26 |
27 |
28 | protocol.setData({
29 | id: this.id || null,
30 | name: this.name,
31 | autorun: this.autorun || []
32 | });
33 |
34 | const request = new HttpRequest(protocol);
35 | const promise = request.execute()
36 | .then(data => {
37 | return JSON.parse(data);
38 | })
39 | .then(response => {
40 | if (response.error) {
41 | return Promise.reject(response);
42 | }
43 | this._extend(response.result);
44 | return this;
45 | });
46 | return Utils.wrapCallbacks(promise, callbacks);
47 | }
48 |
49 | remove(callbacks = {}) {
50 | let protocolOpts = {
51 | url: SDKOptions.REMOVE_INSTANCE_URL
52 | };
53 | const protocol = Protocol.init(protocolOpts);
54 | protocol.setData({
55 | id: this.id
56 | });
57 |
58 | const request = new HttpRequest(protocol);
59 | const promise = request.execute()
60 | .then(data => {
61 | return JSON.parse(data);
62 | })
63 | .then(response => {
64 | if (response.error) {
65 | return Promise.reject(response);
66 | }
67 | return response.result;
68 | });
69 | return Utils.wrapCallbacks(promise, callbacks);
70 | }
71 |
72 | run(callbacks = {}) {
73 | let protocolOpts = {
74 | url: SDKOptions.RUN_INSTANCE_URL
75 | };
76 | const protocol = Protocol.init(protocolOpts);
77 | protocol.setData({
78 | id: this.id
79 | });
80 |
81 | const request = new HttpRequest(protocol);
82 | const promise = request.execute()
83 | .then(data => {
84 | return JSON.parse(data);
85 | })
86 | .then(response => {
87 | if (response.error) {
88 | return Promise.reject(response);
89 | }
90 |
91 | return response.result;
92 | });
93 | return Utils.wrapCallbacks(promise, callbacks);
94 | }
95 |
96 | stop(callbacks = {}) {
97 | let protocolOpts = {
98 | url: SDKOptions.STOP_INSTANCE_URL
99 | };
100 | const protocol = Protocol.init(protocolOpts);
101 | protocol.setData({
102 | id: this.id
103 | });
104 |
105 | const request = new HttpRequest(protocol);
106 | const promise = request.execute()
107 | .then(data => {
108 | return JSON.parse(data);
109 | })
110 | .then(response => {
111 | if (response.error) {
112 | return Promise.reject(response);
113 | }
114 |
115 | return response.result;
116 | });
117 | return Utils.wrapCallbacks(promise, callbacks);
118 | }
119 |
120 | runScript(path, pool = {}, callbacks = {}) {
121 | let protocolOpts = {
122 | url: SDKOptions.RUN_SCRIPT_INSTANCE_URL
123 | };
124 | const protocol = Protocol.init(protocolOpts);
125 | protocol.setData({
126 | id: this.id,
127 | path: path,
128 | pool: pool
129 | });
130 |
131 | const request = new HttpRequest(protocol);
132 | const promise = request.execute()
133 | .then(data => {
134 | return JSON.parse(data);
135 | })
136 | .then(response => {
137 | if (response.error) {
138 | return Promise.reject(response);
139 | }
140 |
141 | return response.result;
142 | });
143 | return Utils.wrapCallbacks(promise, callbacks);
144 | }
145 |
146 | killScript(pid, callbacks = {}) {
147 | let protocolOpts = {
148 | url: SDKOptions.KILL_SCRIPT_INSTANCE_URL
149 | };
150 | const protocol = Protocol.init(protocolOpts);
151 | protocol.setData({
152 | id: this.id,
153 | pid: pid
154 | });
155 |
156 | const request = new HttpRequest(protocol);
157 | const promise = request.execute()
158 | .then(data => {
159 | return JSON.parse(data);
160 | })
161 | .then(response => {
162 | if (response.error) {
163 | return Promise.reject(response);
164 | }
165 |
166 | return response.result;
167 | });
168 | return Utils.wrapCallbacks(promise, callbacks);
169 | }
170 |
171 | getScripts(callbacks = {}) {
172 | let protocolOpts = {
173 | url: SDKOptions.SCRIPTS_INSTANCE_URL
174 | };
175 | const protocol = Protocol.init(protocolOpts);
176 | protocol.setData({
177 | id: this.id
178 | });
179 |
180 | const request = new HttpRequest(protocol);
181 | const promise = request.execute()
182 | .then(data => {
183 | return JSON.parse(data);
184 | })
185 | .then(response => {
186 | if (response.error) {
187 | return Promise.reject(response);
188 | }
189 |
190 | return response.result;
191 | });
192 | return Utils.wrapCallbacks(promise, callbacks);
193 | }
194 |
195 | }
--------------------------------------------------------------------------------
/dist/client.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
8 |
9 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
10 |
11 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12 |
13 | var sharedInstance = void 0;
14 | var SDKOptions = exports.SDKOptions = {
15 | WSHOST: 'wss.scorocode.ru',
16 | WS_PROTOCOL: 'wss',
17 | HOST: 'api.scorocode.ru',
18 | PORT: '443',
19 |
20 | CREATE_INSTANCE_URL: '/api/v1/instance/create',
21 | UPDATE_INSTANCE_URL: '/api/v1/instance/update',
22 | REMOVE_INSTANCE_URL: '/api/v1/instance/delete',
23 | RUN_INSTANCE_URL: '/api/v1/instance/run',
24 | STOP_INSTANCE_URL: '/api/v1/instance/stop',
25 | LIST_INSTANCE_URL: '/api/v1/instance',
26 | SCRIPTS_INSTANCE_URL: '/api/v1/instance/scripts',
27 | RUN_SCRIPT_INSTANCE_URL: '/api/v1/instance/scripts/run',
28 | KILL_SCRIPT_INSTANCE_URL: '/api/v1/instance/scripts/delete',
29 |
30 | GET_AUTH_URL: '/api/v1/verifylogin',
31 |
32 | FIND_URL: '/api/v1/data/find',
33 | COUNT_URL: '/api/v1/data/count',
34 | UPDATE_URL: '/api/v1/data/update',
35 | UPDATE_BY_ID_URL: '/api/v1/data/updatebyid',
36 | REMOVE_URL: '/api/v1/data/remove',
37 | INSERT_URL: '/api/v1/data/insert',
38 |
39 | SEND_PUSH_URL: '/api/v1/sendpush',
40 | SEND_SMS_URL: '/api/v1/sendsms',
41 |
42 | CLOUD_CODE_URL: '/api/v1/scripts',
43 |
44 | UPLOAD_URL: '/api/v1/upload',
45 | REMOVE_FILE_URL: '/api/v1/deletefile',
46 | GET_FILE_LINK_URL: '',
47 |
48 | SIGN_UP_URL: '/api/v1/register',
49 | LOGOUT_URL: '/api/v1/logout',
50 | LOGIN_URL: '/api/v1/login',
51 |
52 | DATA_STATS: '/api/v1/stat',
53 |
54 | BOT_HOST: 'bots.scorocode.ru',
55 | BOT_URL: '/bots/',
56 |
57 | /* Работа с приложением */
58 | GET_APP_URL: '/api/v1/app',
59 | UPDATE_APP_KEY: '/api/v1/app/keys/update',
60 | GET_COLLECTIONS_URL: '/api/v1/app/collections',
61 | GET_COLLECTION_URL: '/api/v1/app/collections/get',
62 | CREATE_COLLECTION_URL: '/api/v1/app/collections/create',
63 | UPDATE_COLLECTION_URL: '/api/v1/app/collections/update',
64 | DELETE_COLLECTION_URL: '/api/v1/app/collections/delete',
65 | CLONE_COLLECTION_URL: '/api/v1/app/collections/clone',
66 | CREATE_INDEX_URL: '/api/v1/app/collections/index/create',
67 | DELETE_INDEX_URL: '/api/v1/app/collections/index/delete',
68 | CREATE_FIELD_URL: '/api/v1/app/collections/fields/create',
69 | UPDATE_FIELD_URL: '/api/v1/app/collections/fields/update',
70 | DELETE_FIELD_URL: '/api/v1/app/collections/fields/delete',
71 | UPDATE_TRIGGERS_URL: '/api/v1/app/collections/triggers',
72 | GET_FOLDERS_URL: '/api/v1/app/scripts/folders',
73 | CREATE_FOLDER_URL: '/api/v1/app/scripts/folders/create',
74 | DELETE_FOLDER_URL: '/api/v1/app/scripts/folders/delete',
75 | GET_SCRIPT_URL: '/api/v1/app/scripts/get',
76 | CREATE_SCRIPT_URL: '/api/v1/app/scripts/create',
77 | UPDATE_SCRIPT_URL: '/api/v1/app/scripts/update',
78 | DELETE_SCRIPT_URL: '/api/v1/app/scripts/delete',
79 | GET_BOTS_URL: '/api/v1/bots',
80 | CREATE_BOT_URL: '/api/v1/bots/create',
81 | UPDATE_BOT_URL: '/api/v1/bots/update',
82 | DELETE_BOT_URL: '/api/v1/bots/delete',
83 | TIMEOUT: 120000
84 |
85 | };
86 |
87 | var Client = exports.Client = function () {
88 | function Client(options) {
89 | _classCallCheck(this, Client);
90 |
91 | if (typeof options.ApplicationID !== 'string') {
92 | throw new Error('Invalid Application ID');
93 | }
94 |
95 | if (typeof options.JavaScriptKey !== 'string') {
96 | throw new Error('Invalid JavaScript Key');
97 | }
98 |
99 | if (options.MasterKey && typeof options.MasterKey !== 'string') {
100 | throw new Error('Invalid MasterKey');
101 | }
102 |
103 | this.middleware = [];
104 |
105 | this.applicationID = options.ApplicationID;
106 | this.clientKey = options.JavaScriptKey;
107 | this.masterKey = options.MasterKey || "";
108 | this.messageKey = options.MessageKey || "";
109 | this.scriptKey = options.ScriptKey || "";
110 | this.fileKey = options.FileKey || "";
111 | this.websocketKey = options.WebSocketKey || "";
112 | this.sessionId = options.sessionId || "";
113 |
114 | this.host = "https://scorocode.ru";
115 | this.port = "443";
116 |
117 | /* Not implemented yet */
118 | if (options.EncryptKey && typeof options.EncryptKey !== 'string') {
119 | throw new Error('Invalid EncryptKey');
120 | }
121 | this.EncryptKey = '';
122 | this.isNode = false;
123 |
124 | if ((typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' && process + '' === '[object process]') {
125 | this.isNode = true;
126 | }
127 | }
128 |
129 | _createClass(Client, [{
130 | key: 'get',
131 | value: function get(key) {
132 | return SDKOptions[key];
133 | }
134 | }, {
135 | key: 'set',
136 | value: function set(key, value) {
137 | SDKOptions[key] = value;
138 | }
139 | }], [{
140 | key: 'init',
141 | value: function init(options) {
142 | var client = new Client(options);
143 | sharedInstance = client;
144 | return client;
145 | }
146 | }, {
147 | key: 'getInstance',
148 | value: function getInstance() {
149 | return sharedInstance;
150 | }
151 | }]);
152 |
153 | return Client;
154 | }();
--------------------------------------------------------------------------------
/dist/cloudCode.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCCloudCode = undefined;
7 |
8 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
9 |
10 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
11 |
12 | var _protocol = require('./protocol');
13 |
14 | var _utils = require('./utils');
15 |
16 | var _httpRequest = require('./httpRequest');
17 |
18 | var _client = require('./client');
19 |
20 | var _websocket = require('./websocket');
21 |
22 | var _logger = require('./logger');
23 |
24 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
25 |
26 | var SCCloudCode = exports.SCCloudCode = function () {
27 | function SCCloudCode(id) {
28 | var _this = this;
29 |
30 | var opt = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
31 |
32 | _classCallCheck(this, SCCloudCode);
33 |
34 | if (typeof id !== 'string') {
35 | throw new Error('Invalid script id');
36 | }
37 | this.debugChannel = ('0' + Math.random() * 10000000).slice(-7);
38 |
39 | if (opt.logger instanceof _logger.SCLogger) {
40 | this.logger = opt.logger;
41 | this._ws = new _websocket.SCWebSocket(this.debugChannel);
42 | this._ws.on("open", function () {});
43 | this._ws.on("error", function (err) {
44 | _this.logger.error(err);
45 | });
46 | this._ws.on("message", function (msg) {
47 | _this.logger.log(msg);
48 | });
49 | }
50 |
51 | this.isRunByPath = !!opt.isRunByPath;
52 | this.id = id;
53 | }
54 |
55 | _createClass(SCCloudCode, [{
56 | key: 'runSync',
57 | value: function runSync() {
58 | var pool = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
59 | var callbacks = arguments[1];
60 |
61 | if ((typeof pool === 'undefined' ? 'undefined' : _typeof(pool)) !== 'object') {
62 | throw new Error('Invalid type of pool');
63 | }
64 |
65 | var protocolOpts = {
66 | url: _client.SDKOptions.CLOUD_CODE_URL
67 | };
68 |
69 | var channelId = parseInt(Math.random() * 10000000);
70 |
71 | var protocol = _protocol.CloudCodeProtocol.init({
72 | script: this.isRunByPath ? "" : this.id,
73 | isRunByPath: this.isRunByPath,
74 | path: this.isRunByPath ? this.id : "",
75 | pool: Object.assign({ channelId: channelId }, pool),
76 | debug: false
77 | }, protocolOpts);
78 |
79 | var promise = new Promise(function (resolve, reject) {
80 | var request = new _httpRequest.HttpRequest(protocol);
81 | var ws = new _websocket.SCWebSocket(channelId);
82 |
83 | var timeout = setTimeout(function () {
84 | ws.wsInstanse.close();
85 | clearTimeout(timeout);
86 | reject({ errMsg: 'Gateway Timeout', errCode: 504, error: true });
87 | }, 120000);
88 |
89 | ws.on("open", function () {
90 | request.execute().then(function (data) {
91 | return JSON.parse(data);
92 | }).then(function (response) {
93 | if (response.error) {
94 | return reject(response);
95 | }
96 | });
97 | });
98 | ws.on("error", function (err) {
99 | return reject(err);
100 | });
101 | ws.on("message", function (msg) {
102 | ws.wsInstanse.close();
103 | clearTimeout(timeout);
104 | return resolve(msg);
105 | });
106 | });
107 |
108 | return _utils.Utils.wrapCallbacks(promise, callbacks);
109 | }
110 | }, {
111 | key: 'run',
112 | value: function run() {
113 | var pool = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
114 | var debug = arguments[1];
115 | var callbacks = arguments[2];
116 |
117 | if ((typeof pool === 'undefined' ? 'undefined' : _typeof(pool)) !== 'object') {
118 | throw new Error('Invalid type of pool');
119 | }
120 |
121 | if ((typeof debug === 'undefined' ? 'undefined' : _typeof(debug)) === 'object') {
122 | callbacks = debug;
123 | }
124 |
125 | var protocolOpts = {
126 | url: _client.SDKOptions.CLOUD_CODE_URL
127 | };
128 |
129 | var protocol = _protocol.CloudCodeProtocol.init({
130 | isRunByPath: this.isRunByPath,
131 | script: this.isRunByPath ? "" : this.id,
132 | path: this.isRunByPath ? this.id : "",
133 | pool: pool,
134 | debug: debug,
135 | debugChannel: this.debugChannel
136 | }, protocolOpts);
137 |
138 | var request = new _httpRequest.HttpRequest(protocol);
139 | var promise = request.execute().then(function (data) {
140 | return JSON.parse(data);
141 | }).then(function (response) {
142 | if (response.error) {
143 | return Promise.reject(response);
144 | }
145 |
146 | return response;
147 | });
148 |
149 | return _utils.Utils.wrapCallbacks(promise, callbacks);
150 | }
151 | }]);
152 |
153 | return SCCloudCode;
154 | }();
--------------------------------------------------------------------------------
/src/stores/networkStore.js:
--------------------------------------------------------------------------------
1 | import {DataProtocol, CloudProtocol} from '../protocol'
2 | import {HttpRequest} from '../httpRequest'
3 | import {Utils} from '../utils'
4 | import {deserializeFast} from '../bson'
5 | import {SDKOptions, Client} from '../client'
6 |
7 | export class Network {
8 | constructor() {}
9 |
10 | find(query, options) {
11 | let protocolOpts = {
12 | url: SDKOptions.FIND_URL
13 | };
14 |
15 | const protocol = DataProtocol.init(query, null, protocolOpts);
16 | const request = new HttpRequest(protocol);
17 | const promise = request.execute()
18 | .then(data => {
19 | return JSON.parse(data);
20 | })
21 | .then(response => {
22 | if (response.error) {
23 | return Promise.reject(response);
24 | }
25 |
26 | let base64Decoded = new Buffer(response.result, 'base64');
27 | let deserializedBson = deserializeFast(base64Decoded, 0, true);
28 |
29 | return {
30 | error: false,
31 | limit: response.limit,
32 | skip: response.skip,
33 | result: deserializedBson.slice()
34 | };
35 | });
36 |
37 | return Utils.wrapCallbacks(promise, options);
38 | }
39 | count(query, options) {
40 | let protocolOpts = {
41 | url: SDKOptions.COUNT_URL
42 | };
43 |
44 | const protocol = DataProtocol.init(query, null, protocolOpts);
45 | const request = new HttpRequest(protocol);
46 | const promise = request.execute()
47 | .then(data => {
48 | return JSON.parse(data);
49 | })
50 | .then(response => {
51 | if (response.error) {
52 | return Promise.reject(response);
53 | }
54 |
55 | return response;
56 | });
57 |
58 | return Utils.wrapCallbacks(promise, options);
59 | }
60 | update(query, doc, options) {
61 | let protocolOpts = {
62 | url: SDKOptions.UPDATE_URL
63 | };
64 |
65 | const protocol = DataProtocol.init(query, doc, protocolOpts);
66 | const request = new HttpRequest(protocol);
67 | const promise = request.execute()
68 | .then(data => {
69 | return JSON.parse(data);
70 | })
71 | .then(response => {
72 | if (response.error) {
73 | return Promise.reject(response);
74 | }
75 |
76 | return response;
77 | });
78 |
79 | return Utils.wrapCallbacks(promise, options);
80 | }
81 | updateById (query, options) {
82 | let protocolOpts = {
83 | url: SDKOptions.UPDATE_BY_ID_URL
84 | };
85 |
86 | const protocol = DataProtocol.init(query, null, protocolOpts);
87 | const request = new HttpRequest(protocol);
88 | const promise = request.execute()
89 | .then(data => {
90 | return JSON.parse(data);
91 | })
92 | .then(response => {
93 | if (response.error) {
94 | return Promise.reject(response);
95 | }
96 |
97 | return response;
98 | });
99 |
100 | return Utils.wrapCallbacks(promise, options);
101 | }
102 | remove(query, options) {
103 | let protocolOpts = {
104 | url: SDKOptions.REMOVE_URL
105 | };
106 |
107 | const protocol = DataProtocol.init(query, null, protocolOpts);
108 | const request = new HttpRequest(protocol);
109 | const promise = request.execute()
110 | .then(data => {
111 | return JSON.parse(data);
112 | })
113 | .then(response => {
114 | if (response.error) {
115 | return Promise.reject(response);
116 | }
117 |
118 | return response.result;
119 | });
120 |
121 | return Utils.wrapCallbacks(promise, options);
122 | }
123 | insert(query, options) {
124 | let protocolOpts = {
125 | url: SDKOptions.INSERT_URL
126 | };
127 |
128 | const protocol = DataProtocol.init(query, null, protocolOpts);
129 | const request = new HttpRequest(protocol);
130 | const promise = request.execute()
131 | .then(data => {
132 | return JSON.parse(data);
133 | })
134 | .then(response => {
135 | if (response.error) {
136 | return Promise.reject(response);
137 | }
138 |
139 | return response;
140 | });
141 |
142 | return Utils.wrapCallbacks(promise, options);
143 | }
144 |
145 | uploadFile(params, options) {
146 | let protocolOpts = {
147 | url: SDKOptions.UPLOAD_URL
148 | };
149 | const client = Client.getInstance();
150 | const protocol = DataProtocol.init(params, null, protocolOpts);
151 |
152 | protocol.setAccessKey('acc', client.masterKey || client.fileKey);
153 |
154 | const request = new HttpRequest(protocol);
155 | const promise = request.execute(options)
156 | .then(data => {
157 | return JSON.parse(data);
158 | })
159 | .then(response => {
160 | if (response.error) {
161 | return Promise.reject(response);
162 | }
163 |
164 | return response;
165 | });
166 |
167 | return Utils.wrapCallbacks(promise, options);
168 | }
169 | removeFile(params, options) {
170 | let protocolOpts = {
171 | url: SDKOptions.REMOVE_FILE_URL
172 | };
173 |
174 | const client = Client.getInstance();
175 | const protocol = DataProtocol.init(params, null, protocolOpts);
176 |
177 | protocol.setAccessKey('acc', client.masterKey || client.fileKey);
178 | const request = new HttpRequest(protocol);
179 | const promise = request.execute()
180 | .then(data => {
181 | return JSON.parse(data);
182 | })
183 | .then(response => {
184 | if (response.error) {
185 | return Promise.reject(response);
186 | }
187 |
188 | return response;
189 | });
190 |
191 | return Utils.wrapCallbacks(promise, options);
192 | }
193 | }
--------------------------------------------------------------------------------
/dist/user.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCUser = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _protocol = require('./protocol');
11 |
12 | var _httpRequest = require('./httpRequest');
13 |
14 | var _utils = require('./utils');
15 |
16 | var _client = require('./client');
17 |
18 | var _object = require('./object');
19 |
20 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
21 |
22 | function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
23 |
24 | function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
25 |
26 | var SCUser = exports.SCUser = function (_SCObject) {
27 | _inherits(SCUser, _SCObject);
28 |
29 | function SCUser(user) {
30 | _classCallCheck(this, SCUser);
31 |
32 | return _possibleConstructorReturn(this, Object.getPrototypeOf(SCUser).call(this, 'users', user));
33 | }
34 |
35 | _createClass(SCUser, [{
36 | key: 'signup',
37 | value: function signup() {
38 | var _this2 = this;
39 |
40 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
41 |
42 | var protocolOpts = {
43 | url: _client.SDKOptions.SIGN_UP_URL
44 | };
45 |
46 | var data = {
47 | username: this.attrs.username,
48 | email: this.attrs.email,
49 | password: this.attrs.password
50 | };
51 | var protocol = _protocol.UserProtocol.init(data, this.attrs, protocolOpts);
52 | var request = new _httpRequest.HttpRequest(protocol);
53 | var promise = request.execute().then(function (response) {
54 | return JSON.parse(response);
55 | }).then(function (response) {
56 | if (response.error) {
57 | return Promise.reject(response);
58 | }
59 |
60 | _utils.Utils.extend(_this2.attrs, response.result);
61 |
62 | return response.result;
63 | });
64 | return _utils.Utils.wrapCallbacks(promise, options);
65 | }
66 | }, {
67 | key: 'logout',
68 | value: function logout() {
69 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
70 |
71 | var protocolOpts = {
72 | url: _client.SDKOptions.LOGOUT_URL
73 | };
74 |
75 | var protocol = _protocol.UserProtocol.init(null, null, protocolOpts);
76 | var request = new _httpRequest.HttpRequest(protocol);
77 | var promise = request.execute().then(function (response) {
78 | return JSON.parse(response);
79 | }).then(function (response) {
80 | if (!response.error) {
81 | var client = _client.Client.getInstance();
82 | client.sessionId = "";
83 | }
84 |
85 | return response;
86 | });
87 | return _utils.Utils.wrapCallbacks(promise, options);
88 | }
89 | }, {
90 | key: 'authorize',
91 | value: function authorize() {
92 | var _this3 = this;
93 |
94 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
95 |
96 | var protocolOpts = {
97 | url: _client.SDKOptions.GET_AUTH_URL
98 | };
99 |
100 | var protocol = _protocol.UserProtocol.init(null, null, protocolOpts);
101 | var request = new _httpRequest.HttpRequest(protocol);
102 | var promise = request.execute().then(function (data) {
103 | return JSON.parse(data);
104 | }).then(function (response) {
105 | if (response.error) {
106 | return Promise.reject(response);
107 | }
108 |
109 | var client = _client.Client.getInstance();
110 | client.sessionId = response.result.sessionId;
111 |
112 | _utils.Utils.extend(_this3.attrs, response.result.user);
113 |
114 | return response.result.user;
115 | });
116 | return _utils.Utils.wrapCallbacks(promise, options);
117 | }
118 | }, {
119 | key: 'login',
120 | value: function login(email, password) {
121 | var _this4 = this;
122 |
123 | var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
124 |
125 | var protocolOpts = {
126 | url: _client.SDKOptions.LOGIN_URL
127 | };
128 |
129 | var protocol = _protocol.UserProtocol.init({ email: email, password: password }, null, protocolOpts);
130 | var request = new _httpRequest.HttpRequest(protocol);
131 | var promise = request.execute().then(function (data) {
132 | return JSON.parse(data);
133 | }).then(function (response) {
134 | if (response.error) {
135 | return Promise.reject(response);
136 | }
137 |
138 | var client = _client.Client.getInstance();
139 | client.sessionId = response.result.sessionId;
140 |
141 | _utils.Utils.extend(_this4.attrs, response.result.user);
142 |
143 | return response.result.user;
144 | });
145 |
146 | return _utils.Utils.wrapCallbacks(promise, options);
147 | }
148 | }]);
149 |
150 | return SCUser;
151 | }(_object.SCObject);
--------------------------------------------------------------------------------
/src/updateOps.js:
--------------------------------------------------------------------------------
1 | import {Utils} from "./utils"
2 |
3 | var operators = {
4 | set: function (key, value) {
5 | if (this instanceof SCUpdateOps || this.attrs['_id']) {
6 | if (key === 'createdAt' || key === 'updatedAt' || key === '_id') {
7 | return this;
8 | }
9 | if (!this.update['$set']) {
10 | this.update['$set'] = {}
11 | }
12 | this.update['$set'][key] = value;
13 |
14 | if (this.attrs) {
15 | this.attrs[key] = value;
16 | }
17 |
18 | } else {
19 | this.attrs[key] = value;
20 | }
21 |
22 | return this;
23 | },
24 | push: function (key, value) {
25 | if (!(this instanceof SCUpdateOps)) {
26 | if (!this.attrs['_id']) {
27 | throw new Error('For a new document use the method Set');
28 | }
29 |
30 | if (!Utils.isArray(this.attrs[key])) {
31 | throw new Error('Field must by a type of array');
32 | }
33 | }
34 |
35 | if (!this.update['$push']) {
36 | this.update['$push'] = {}
37 | }
38 | this.update['$push'][key] = value;
39 |
40 | return this;
41 | },
42 | pull: function (key, value) {
43 | if (!(this instanceof SCUpdateOps)) {
44 | if (!this.attrs['_id']) {
45 | throw new Error('For a new document use the method Set');
46 | }
47 | }
48 |
49 | if (!this.update['$pull']) {
50 | this.update['$pull'] = {}
51 | }
52 | this.update['$pull'][key] = value;
53 |
54 | return this;
55 | },
56 | pullAll: function (key, value) {
57 | if (!(this instanceof SCUpdateOps)) {
58 | if (!this.attrs['_id']) {
59 | throw new Error('For a new document use the method Set');
60 | }
61 | }
62 |
63 | if (!Utils.isArray(value)) {
64 | throw new Error('Value must by a type of array');
65 | }
66 |
67 | if (!this.update['$pullAll']) {
68 | this.update['$pullAll'] = {}
69 | }
70 | this.update['$pullAll'][key] = value;
71 |
72 | return this;
73 | },
74 | addToSet: function (key, value) {
75 | if (!(this instanceof SCUpdateOps)) {
76 | if (!this.attrs['_id']) {
77 | throw new Error('For a new document use the method Set');
78 | }
79 | }
80 |
81 | if (!this.update['$addToSet']) {
82 | this.update['$addToSet'] = {}
83 | }
84 | this.update['$addToSet'][key] = value;
85 |
86 | return this;
87 | },
88 | pop: function (key, pos) {
89 | if (!(this instanceof SCUpdateOps)) {
90 | if (!this.attrs['_id']) {
91 | throw new Error('For a new document use the method Set');
92 | }
93 |
94 | if (!Utils.isArray(this.attrs[key])) {
95 | throw new Error('Field must by a type of array');
96 | }
97 | }
98 |
99 | if (pos !== 1 && pos !== -1) {
100 | throw new Error('Position must be 1 or -1');
101 | }
102 |
103 | if (!this.update['$pop']) {
104 | this.update['$pop'] = {}
105 | }
106 | this.update['$pop'][key] = pos;
107 |
108 | return this;
109 | },
110 | inc: function (key, value) {
111 | if (!(this instanceof SCUpdateOps)) {
112 | if (!this.attrs['_id']) {
113 | throw new Error('For a new document use the method Set');
114 | }
115 | }
116 |
117 | if (!this.update['$inc']) {
118 | this.update['$inc'] = {}
119 | }
120 | this.update['$inc'][key] = value;
121 |
122 | return this;
123 | },
124 | currentDate: function (key, type) {
125 | if (!(this instanceof SCUpdateOps)) {
126 | if (!this.attrs['_id']) {
127 | throw new Error('For a new document use the method Set');
128 | }
129 |
130 | if (type !== true && type !== 'timestamp' && type !== 'date') {
131 | throw new Error('Invalid type');
132 | }
133 | }
134 |
135 | if (!this.update['$currentDate']) {
136 | this.update['$currentDate'] = {}
137 | }
138 |
139 | if (type === 'timestamp' || type === 'date') {
140 | this.update['$currentDate'][key] = {$type: type};
141 | } else {
142 | this.update['$currentDate'][key] = type;
143 | }
144 |
145 |
146 | return this;
147 | },
148 | mul: function (key, value) {
149 | if (!(this instanceof SCUpdateOps)) {
150 | if (!this.attrs['_id']) {
151 | throw new Error('For a new document use the method Set');
152 | }
153 |
154 | if (!Utils.isNumber(this.attrs[key])) {
155 | throw new Error('Field must by a type of number');
156 | }
157 | }
158 |
159 | if (!Utils.isNumber(value)) {
160 | throw new Error('Value must by a type of number');
161 | }
162 |
163 | if (!this.update['$mul']) {
164 | this.update['$mul'] = {}
165 | }
166 |
167 | this.update['$mul'][key] = value;
168 |
169 | return this;
170 | },
171 | min: function (key, value) {
172 | if (!(this instanceof SCUpdateOps)) {
173 | if (!this.attrs['_id']) {
174 | throw new Error('For a new document use the method Set');
175 | }
176 |
177 | if (!Utils.isNumber(this.attrs[key])) {
178 | throw new Error('Field must by a type of number');
179 | }
180 | }
181 |
182 | if (!Utils.isNumber(value)) {
183 | throw new Error('Value must by a type of number');
184 | }
185 |
186 | if (!this.update['$min']) {
187 | this.update['$min'] = {}
188 | }
189 |
190 | this.update['$min'][key] = value;
191 |
192 | return this;
193 | },
194 | max: function (key, value) {
195 | if (!(this instanceof SCUpdateOps)) {
196 | if (!this.attrs['_id']) {
197 | throw new Error('For a new document use the method Set');
198 | }
199 |
200 | if (!Utils.isNumber(this.attrs[key])) {
201 | throw new Error('Field must by a type of number');
202 | }
203 | }
204 |
205 | if (!Utils.isNumber(value)) {
206 | throw new Error('Value must by a type of number');
207 | }
208 |
209 | if (!this.update['$max']) {
210 | this.update['$max'] = {}
211 | }
212 |
213 | this.update['$max'][key] = value;
214 |
215 | return this;
216 | }
217 | };
218 |
219 |
220 |
221 | class SCUpdateOps {
222 | constructor() {
223 | this.update = {};
224 | for (let prop in operators) {
225 | this[prop] = operators[prop];
226 | }
227 | }
228 |
229 | toJson() {
230 | const json = this.update;
231 | return json;
232 | }
233 | }
234 |
235 |
236 |
237 | export {operators, SCUpdateOps}
--------------------------------------------------------------------------------
/src/bson.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | /*
3 | * https://github.com/mongodb/js-bson/blob/master/alternate_parsers/faster_bson.js
4 | * */
5 |
6 | const JS_INT_MAX = 0x20000000000000;
7 | const JS_INT_MIN = -0x20000000000000;
8 |
9 | var Long = require('./long');
10 | var ObjectID = require('./objectid');
11 |
12 | function Timestamp(low, high) {
13 | this._bsontype = 'Timestamp';
14 | this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits.
15 | }
16 | Timestamp.prototype.getLowBits = function(){ return this.low_; }
17 | Timestamp.prototype.getHighBits = function(){ return this.high_; }
18 |
19 |
20 | function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!?
21 |
22 | function MaxKey() { this._bsontype = 'MaxKey'; }
23 |
24 |
25 | function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options!
26 | if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw'
27 | var elementType, tempindex = 0, name;
28 | var string, low, high; /// = lowBits / highBits
29 | /// using 'i' as the index to keep the lines shorter:
30 | i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion
31 | var object = isArray ? [] : {}; /// needed for type ARRAY recursion later!
32 | var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
33 | if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message');
34 | /// 'size' var was not used by anything after this, so we can reuse it
35 |
36 | while(true) { // While we have more left data left keep parsing
37 | elementType = buffer[i++]; // Read the type
38 | if (elementType === 0) break; // If we get a zero it's the last byte, exit
39 |
40 | tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString')
43 | name = buffer.toString('utf8', i, tempindex);
44 | i = tempindex + 1; /// Update index position to after the string + '0' termination
45 |
46 | switch(elementType) {
47 |
48 | case 7: /// = BSON.BSON_DATA_OID:
49 | var buf = new Buffer(12);
50 | buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer
51 | object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance
52 | break;
53 |
54 | case 2: /// = BSON.BSON_DATA_STRING:
55 | size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24;
56 | object[name] = buffer.toString('utf8', i, i += size -1 );
57 | i++; break; /// need to get the '0' index "tick-forward" back!
58 |
59 | case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value
60 | object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break;
61 |
62 | case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value
63 | object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner
64 | /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8);
65 | i += 8; break;
66 |
67 | case 8: /// = BSON.BSON_DATA_BOOLEAN:
68 | object[name] = buffer[i++] == 1; break;
69 |
70 | case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated
71 | case 10: /// = BSON.BSON_DATA_NULL:
72 | object[name] = null; break;
73 |
74 | case 4: /// = BSON.BSON_DATA_ARRAY
75 | size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion!
76 | object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true
77 | i += size; break;
78 | case 3: /// = BSON.BSON_DATA_OBJECT:
79 | size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24;
80 | object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object
81 | i += size; break;
82 |
83 | case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob
84 | size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
85 | buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0!
86 | object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory!
87 | break;
88 |
89 | case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options...
90 | low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
91 | high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
92 | object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break;
93 |
94 | case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits:
95 | low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
96 | high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
97 |
98 | size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber()
99 | if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely!
100 | else object[name] = new Long(low, high); break;
101 |
102 | case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?!
103 | object[name] = new MinKey(); break;
104 | case 255: /// = BSON.BSON_DATA_MAX_KEY:
105 | object[name] = new MaxKey(); break;
106 |
107 | case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc.
108 | low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
109 | high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
110 | object[name] = new Timestamp(low, high); break;
111 |
112 | /// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!?
113 | } /// end of switch(elementType)
114 | } /// end of while(1)
115 | return object; // Return the finalized object
116 | }
117 |
118 | export {deserializeFast}
--------------------------------------------------------------------------------
/src/query.js:
--------------------------------------------------------------------------------
1 | import {Utils} from "./utils"
2 | import {DataStore} from "./stores/data"
3 |
4 | export class SCQuery {
5 | constructor (collName) {
6 | if (typeof collName !== 'string') {
7 | throw new Error('Collection name must be a type of string');
8 | }
9 | this._collection = collName;
10 | this._fields = [];
11 | this._filter = {};
12 | this._sort = {};
13 | this._limit = 100;
14 | this._skip = 0;
15 | }
16 |
17 | _addFilter(field, condition, values) {
18 | if (!Utils.isObject(this._filter[field])) {
19 | this._filter[field] = {};
20 | }
21 |
22 | if (typeof condition === 'object') {
23 | this._filter[field] = condition;
24 | return this;
25 | }
26 |
27 | this._filter[field][condition] = values;
28 | return this;
29 | }
30 |
31 | find(options = {}) {
32 | //TODO: Следует возвращать массив SC.Object вместо сырых данных
33 | return DataStore.getInstance().find(this.toJson(), options);
34 | }
35 |
36 | // Не следует использовать для больших коллекций
37 | findAll(options = {}) {
38 | let result = [];
39 | return Utils.promiseWhile(
40 | (res) => {
41 | if (!res) {
42 | return true;
43 | }
44 |
45 | if (!res.result.length) {
46 | return false;
47 | }
48 |
49 | result = result.concat(res.result);
50 | this.skip(this._skip + this._limit);
51 |
52 | return true;
53 | },
54 | () => {
55 | return DataStore.getInstance().find(this.toJson(), options);
56 | })
57 | .then(res => result)
58 | }
59 | count(options = {}) {
60 | return DataStore.getInstance().count(this.toJson(), options);
61 | }
62 | update(object, options = {}) {
63 | return DataStore.getInstance().update(this.toJson(), object.toJson(), options);
64 | }
65 | remove(options = {}) {
66 | return DataStore.getInstance().remove(this.toJson(), options);
67 | }
68 |
69 | reset() {
70 | this._filter = {};
71 | this.fields = [];
72 |
73 | return this;
74 | }
75 |
76 | equalTo(field, value) {
77 | this._filter[field] = value;
78 | return this;
79 | }
80 | notEqualTo(field, value) {
81 | return this._addFilter(field, "$ne", value);
82 | }
83 |
84 | containedIn(field,value) {
85 | if (!Utils.isArray(value)) {
86 | throw new Error('Value must be of type: Array');
87 | }
88 |
89 | return this._addFilter(field, '$in', value);
90 | }
91 | containsAll(field, value) {
92 | if (!Utils.isArray(value)) {
93 | throw new Error('Value must be of type: Array');
94 | }
95 |
96 | return this._addFilter(field, '$all', value);
97 | }
98 | notContainedIn(field, value) {
99 | if (!Utils.isArray(value)) {
100 | throw new Error('Value must be of type: Array');
101 | }
102 |
103 | return this._addFilter(field, '$nin', value);
104 | }
105 |
106 | greaterThan(field, value) {
107 | return this._addFilter(field, '$gt', value);
108 | }
109 | greaterThanOrEqualTo(field, value) {
110 | return this._addFilter(field, '$gte', value);
111 | }
112 | lessThan(field, value) {
113 | return this._addFilter(field, '$lt', value);
114 | }
115 | lessThanOrEqualTo(field, value) {
116 | return this._addFilter(field, '$lte', value);
117 | }
118 |
119 | exists(field) {
120 | return this._addFilter(field, '$exists', true);
121 | }
122 | doesNotExist(field) {
123 | return this._addFilter(field, '$exists', false);
124 | }
125 |
126 | contains(field,value, opts) {
127 | if (opts) {
128 | return this._addFilter(field, {$regex: value, $options: opts});
129 | }
130 |
131 | return this._addFilter(field, '$regex', value);
132 | }
133 |
134 | startsWith(field, value, opts) {
135 | if (typeof value !== 'string') {
136 | throw new Error("Value must be a string");
137 | }
138 |
139 | if (opts) {
140 | return this._addFilter(field, {$regex: '^' + value, $options: opts});
141 | }
142 |
143 | return this._addFilter(field, '$regex', '^' + value);
144 | }
145 |
146 | endsWith(field, value, opts) {
147 | if (typeof value !== 'string') {
148 | throw new Error("Value must be a string");
149 | }
150 |
151 | if (opts) {
152 | return this._addFilter(field, {$regex: value + '$', $options: opts});
153 | }
154 |
155 | return this._addFilter(field, '$regex', value + '$');
156 | }
157 |
158 | limit(limit) {
159 | if (!Utils.isNumber(limit) || limit < 0) {
160 | throw new Error("Limit must be a positive number");
161 | }
162 |
163 | this._limit = limit;
164 |
165 | return this;
166 | }
167 | skip(skip) {
168 | if (!Utils.isNumber(skip) || skip < 0 ) {
169 | throw new Error("Skip must be a positive number");
170 | }
171 |
172 | this._skip = skip;
173 |
174 | return this;
175 | }
176 | page(page) {
177 | if (!Utils.isNumber(page) || page < 0 ) {
178 | throw new Error("Page must be a positive number");
179 | }
180 |
181 | this._skip = (page - 1) * this._limit;
182 |
183 | return this;
184 | }
185 |
186 | ascending(field) {
187 | this._sort[field] = 1;
188 |
189 | return this;
190 | }
191 | descending(field) {
192 | this._sort[field] = -1;
193 |
194 | return this;
195 | }
196 |
197 | or(query) {
198 | if (!(query instanceof SCQuery)) {
199 | throw new Error('Invalid type of Query');
200 | }
201 |
202 | if (!this._filter['$or']) {
203 | this._filter['$or'] = [];
204 | }
205 |
206 | this._filter['$or'].push(query.toJson().query);
207 |
208 | return this;
209 |
210 | }
211 | and(query) {
212 | if (!(query instanceof SCQuery)) {
213 | throw new Error('Invalid type of Query');
214 | }
215 |
216 | if (!this._filter['$and']) {
217 | this._filter['$and'] = [];
218 | }
219 |
220 | this._filter['$and'].push(query.toJson().query);
221 |
222 | return this;
223 | }
224 |
225 | select() {
226 | this._fields = [];
227 | let ln = arguments.length;
228 |
229 | for (let i = 0; i < ln; i++) {
230 | this._fields.push(arguments[i]);
231 | }
232 |
233 | return this;
234 | }
235 |
236 | raw(filter) {
237 | if (!Utils.isObject(filter)) {
238 | throw new Error('Filter must be a object');
239 | }
240 | this._filter = filter;
241 |
242 | return this;
243 | }
244 |
245 | toJson() {
246 | const json = {
247 | coll: this._collection,
248 | limit: this._limit,
249 | skip: this._skip,
250 | query: this._filter,
251 | sort: this._sort,
252 | fields: this._fields
253 | };
254 |
255 | return json;
256 | }
257 | }
--------------------------------------------------------------------------------
/dist/httpRequest.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.HttpRequest = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _observer = require('./observer');
11 |
12 | var _observer2 = _interopRequireDefault(_observer);
13 |
14 | var _client = require('./client');
15 |
16 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 |
18 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
19 |
20 | var https = null;
21 | if (typeof XMLHttpRequest === 'undefined') {
22 | https = require('https');
23 | }
24 |
25 | var HttpRequest = exports.HttpRequest = function () {
26 | function HttpRequest(options) {
27 | _classCallCheck(this, HttpRequest);
28 |
29 | this.method = "";
30 | this.port = "";
31 | this.path = "";
32 | this.host = "";
33 | this.data = "";
34 | this.headers = {};
35 |
36 | var protocolJson = options.toJson();
37 |
38 | for (var prop in protocolJson) {
39 | this[prop] = protocolJson[prop];
40 | }
41 | }
42 |
43 | _createClass(HttpRequest, [{
44 | key: 'node_request',
45 | value: function node_request() {
46 | var _this = this;
47 |
48 | var promise = new Promise(function (resolve, reject) {
49 | var request = https.request({
50 | method: _this.method,
51 | port: _this.port,
52 | path: _this.path,
53 | host: _this.host,
54 | headers: _this.headers
55 | }, function (res) {
56 | var result = "";
57 | if (res.statusCode !== 200) {
58 | return reject({
59 | error: true,
60 | errCode: res.statusCode,
61 | errMsg: res.responseText || 'Invalid statusCode'
62 | });
63 | }
64 |
65 | res.on('data', function (data) {
66 | result += data.toString();
67 | });
68 |
69 | res.on('error', function (err) {
70 | return reject({
71 | error: true,
72 | errCode: res.statusCode,
73 | errMsg: err.message
74 | });
75 | });
76 |
77 | res.on('end', function () {
78 | return resolve(result);
79 | });
80 | });
81 |
82 | request.on('aborted', function () {
83 | return reject({
84 | error: true,
85 | errCode: 504,
86 | errMsg: 'Request has been aborted by the server'
87 | });
88 | });
89 |
90 | request.on('abort', function () {
91 | return reject({
92 | error: true,
93 | errCode: 418,
94 | errMsg: 'Request has been aborted by the client'
95 | });
96 | });
97 |
98 | request.on('error', function (err) {
99 | return reject({
100 | error: true,
101 | errCode: 422,
102 | errMsg: err.message
103 | });
104 | });
105 |
106 | request.setTimeout(_this.timeout, function () {
107 | request.abort();
108 | });
109 |
110 | request.write(_this.data);
111 | request.end();
112 | });
113 | return promise;
114 | }
115 | }, {
116 | key: 'ajax',
117 | value: function ajax() {
118 | var _this2 = this;
119 |
120 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
121 |
122 | var promise = new Promise(function (resolve, reject) {
123 | var url = 'https://' + _this2.host + _this2.path;
124 | var xhr = new XMLHttpRequest();
125 |
126 | xhr.timeout = _this2.timeout;
127 | xhr.open(_this2.method, url, true);
128 |
129 | for (var prop in _this2.headers) {
130 | xhr.setRequestHeader(prop, _this2.headers[prop]);
131 | }
132 |
133 | xhr.onreadystatechange = function () {
134 | if (xhr.readyState != 4) return;
135 | if (xhr.status != 200) {
136 | return reject(new Error('Invalid statusCode: ' + xhr.status));
137 | } else {
138 | resolve(xhr.responseText);
139 | }
140 | };
141 | options.onXHRPrepare && options.onXHRPrepare(xhr);
142 | xhr.send(_this2.data);
143 | });
144 |
145 | return promise;
146 | }
147 | }, {
148 | key: 'request',
149 | value: function request() {
150 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
151 |
152 | if (typeof XMLHttpRequest !== 'undefined') {
153 | return this.ajax(options);
154 | }
155 | return this.node_request();
156 | }
157 | }, {
158 | key: 'execute',
159 | value: function execute() {
160 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
161 |
162 | var client = _client.Client.getInstance();
163 |
164 | var wrap = function wrap(fn) {
165 | return function () {
166 | return fn().then(function (data) {
167 | return JSON.parse(data);
168 | }).then(function (res) {
169 | if (res.error) {
170 | return Promise.reject(res);
171 | }
172 |
173 | return Promise.resolve(JSON.stringify(res));
174 | }).catch(function (err) {
175 | (0, _observer2.default)().emit('error', err);
176 | return Promise.reject(err);
177 | });
178 | };
179 | };
180 |
181 | var fn = wrap(this.request.bind(this));
182 |
183 | for (var i = 0; i < client.middleware.length; i++) {
184 | fn = client.middleware[i](fn);
185 | }
186 |
187 | return fn(options);
188 | }
189 | }]);
190 |
191 | return HttpRequest;
192 | }();
--------------------------------------------------------------------------------
/dist/bson.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | /*
3 | * https://github.com/mongodb/js-bson/blob/master/alternate_parsers/faster_bson.js
4 | * */
5 |
6 | Object.defineProperty(exports, "__esModule", {
7 | value: true
8 | });
9 | var JS_INT_MAX = 0x20000000000000;
10 | var JS_INT_MIN = -0x20000000000000;
11 |
12 | var Long = require('./long');
13 | var ObjectID = require('./objectid');
14 |
15 | function Timestamp(low, high) {
16 | this._bsontype = 'Timestamp';
17 | this.low_ = low | 0;this.high_ = high | 0; /// force into 32 signed bits.
18 | }
19 | Timestamp.prototype.getLowBits = function () {
20 | return this.low_;
21 | };
22 | Timestamp.prototype.getHighBits = function () {
23 | return this.high_;
24 | };
25 |
26 | function MinKey() {
27 | this._bsontype = 'MinKey';
28 | } /// these are merely placeholders/stubs to signify the type!?
29 |
30 | function MaxKey() {
31 | this._bsontype = 'MaxKey';
32 | }
33 |
34 | function deserializeFast(buffer, i, isArray) {
35 | //// , options, isArray) { //// no more options!
36 | if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw'
37 | var elementType,
38 | tempindex = 0,
39 | name;
40 | var string, low, high; /// = lowBits / highBits
41 | /// using 'i' as the index to keep the lines shorter:
42 | i || (i = 0); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion
43 | var object = isArray ? [] : {}; /// needed for type ARRAY recursion later!
44 | var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
45 | if (size < 5 || size > buffer.length) return new Error('Corrupt BSON message');
46 | /// 'size' var was not used by anything after this, so we can reuse it
47 |
48 | while (true) {
49 | // While we have more left data left keep parsing
50 | elementType = buffer[i++]; // Read the type
51 | if (elementType === 0) break; // If we get a zero it's the last byte, exit
52 |
53 | tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString');
58 | name = buffer.toString('utf8', i, tempindex);
59 | i = tempindex + 1; /// Update index position to after the string + '0' termination
60 |
61 | switch (elementType) {
62 |
63 | case 7:
64 | /// = BSON.BSON_DATA_OID:
65 | var buf = new Buffer(12);
66 | buffer.copy(buf, 0, i, i += 12); /// copy 12 bytes from the current 'i' offset into fresh Buffer
67 | object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance
68 | break;
69 |
70 | case 2:
71 | /// = BSON.BSON_DATA_STRING:
72 | size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
73 | object[name] = buffer.toString('utf8', i, i += size - 1);
74 | i++;break; /// need to get the '0' index "tick-forward" back!
75 |
76 | case 16:
77 | /// = BSON.BSON_DATA_INT: // Decode the 32bit value
78 | object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;break;
79 |
80 | case 1:
81 | /// = BSON.BSON_DATA_NUMBER: // Decode the double value
82 | object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner
83 | /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8);
84 | i += 8;break;
85 |
86 | case 8:
87 | /// = BSON.BSON_DATA_BOOLEAN:
88 | object[name] = buffer[i++] == 1;break;
89 |
90 | case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated
91 | case 10:
92 | /// = BSON.BSON_DATA_NULL:
93 | object[name] = null;break;
94 |
95 | case 4:
96 | /// = BSON.BSON_DATA_ARRAY
97 | size = buffer[i] | buffer[i + 1] << 8 | buffer[i + 2] << 16 | buffer[i + 3] << 24; /// NO 'i' increment since the size bytes are reread during the recursion!
98 | object[name] = deserializeFast(buffer, i, true); /// pass current index & set isArray = true
99 | i += size;break;
100 | case 3:
101 | /// = BSON.BSON_DATA_OBJECT:
102 | size = buffer[i] | buffer[i + 1] << 8 | buffer[i + 2] << 16 | buffer[i + 3] << 24;
103 | object[name] = deserializeFast(buffer, i, false); /// isArray = false => Object
104 | i += size;break;
105 |
106 | case 5:
107 | /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob
108 | size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
109 | buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0!
110 | object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory!
111 | break;
112 |
113 | case 9:
114 | /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options...
115 | low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
116 | high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
117 | object[name] = new Date(high * 4294967296 + (low < 0 ? low + 4294967296 : low));break;
118 |
119 | case 18:
120 | /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits:
121 | low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
122 | high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
123 |
124 | size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber()
125 | if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely!
126 | else object[name] = new Long(low, high);break;
127 |
128 | case 127:
129 | /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?!
130 | object[name] = new MinKey();break;
131 | case 255:
132 | /// = BSON.BSON_DATA_MAX_KEY:
133 | object[name] = new MaxKey();break;
134 |
135 | case 17:
136 | /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc.
137 | low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
138 | high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24;
139 | object[name] = new Timestamp(low, high);break;
140 |
141 | /// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!?
142 | } /// end of switch(elementType)
143 | } /// end of while(1)
144 | return object; // Return the finalized object
145 | }
146 |
147 | exports.deserializeFast = deserializeFast;
--------------------------------------------------------------------------------
/dist/object.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCObject = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _query = require("./query");
11 |
12 | var _utils = require("./utils");
13 |
14 | var _updateOps = require("./updateOps");
15 |
16 | var _data = require("./stores/data");
17 |
18 | var _client = require("./client");
19 |
20 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
21 |
22 | var SCObject = exports.SCObject = function () {
23 | function SCObject(collName, model) {
24 | _classCallCheck(this, SCObject);
25 |
26 | if (typeof collName !== 'string') {
27 | throw new Error('Invalid collection name');
28 | }
29 |
30 | this.collection = collName;
31 | this.attrs = Object.assign({}, model);
32 | this.update = {};
33 |
34 | for (var prop in _updateOps.operators) {
35 | this[prop] = _updateOps.operators[prop];
36 | }
37 | }
38 |
39 | _createClass(SCObject, [{
40 | key: "setAttrs",
41 | value: function setAttrs(obj) {
42 | var model = Object.assign({}, obj);
43 | for (var item in model) {
44 | this.set(item, model[item]);
45 | }
46 | }
47 | }, {
48 | key: "getAttrs",
49 | value: function getAttrs() {
50 | return Object.assign({}, this.attrs);
51 | }
52 | }, {
53 | key: "getById",
54 | value: function getById(id, options) {
55 | var _this = this;
56 |
57 | var query = new _query.SCQuery(this.collection);
58 |
59 | if (!id) {
60 | throw new Error('Id is empty');
61 | }
62 |
63 | var promise = query.equalTo('_id', id).find(options).then(function (data) {
64 | if (!data.result.length) {
65 | throw new Error('Document not found');
66 | }
67 |
68 | _this.attrs = {};
69 | _utils.Utils.extend(_this.attrs, data.result[0]);
70 |
71 | return data.result[0];
72 | });
73 |
74 | return promise;
75 | }
76 | }, {
77 | key: "get",
78 | value: function get(key) {
79 | return this.attrs[key];
80 | }
81 | }, {
82 | key: "getFileLink",
83 | value: function getFileLink(field) {
84 | if (!this.attrs['_id']) {
85 | throw new Error('You must first create a document and upload file');
86 | }
87 |
88 | if (!this.attrs.hasOwnProperty(field)) {
89 | throw new Error('Unknown field');
90 | }
91 |
92 | if (!this.attrs[field]) {
93 | throw new Error('Field is empty');
94 | }
95 |
96 | var client = _client.Client.getInstance();
97 | return 'https://api.scorocode.ru/api/v1/getfile/' + client.applicationID + '/' + this.collection + '/' + field + '/' + this.attrs._id + '/' + this.attrs[field];
98 | }
99 | }, {
100 | key: "removeFile",
101 | value: function removeFile(field) {
102 | var _this2 = this;
103 |
104 | var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
105 |
106 | if (!this.attrs['_id']) {
107 | throw new Error('You must first create a document and upload file');
108 | }
109 |
110 | if (!this.attrs.hasOwnProperty(field)) {
111 | throw new Error('Unknown field');
112 | }
113 |
114 | if (!this.attrs[field]) {
115 | throw new Error('Field is empty');
116 | }
117 |
118 | var QueryJSON = this.toJson();
119 | var params = {
120 | coll: QueryJSON.coll,
121 | docId: this.attrs['_id'],
122 | field: field,
123 | file: this.attrs[field]
124 | };
125 | return _data.DataStore.getInstance().removeFile(params, options).then(function (data) {
126 | if (!data.error) {
127 | _this2.attrs[field] = '';
128 | }
129 | return data;
130 | });
131 | }
132 | }, {
133 | key: "uploadFile",
134 | value: function uploadFile(field, filename, file) {
135 | var _this3 = this;
136 |
137 | var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
138 |
139 | if (!this.attrs['_id']) {
140 | throw new Error('You must first create a document');
141 | }
142 |
143 | var base64 = file.split(',');
144 | var base64result = "";
145 |
146 | if (base64.length == 2) {
147 | base64result = base64[1];
148 | } else {
149 | base64result = base64[0];
150 | }
151 |
152 | var QueryJSON = this.toJson();
153 |
154 | var params = {
155 | coll: QueryJSON.coll,
156 | docId: this.attrs['_id'],
157 | field: field,
158 | file: filename,
159 | content: base64result
160 | };
161 | return _data.DataStore.getInstance().uploadFile(params, options).then(function (data) {
162 |
163 | if (!data.error) {
164 | _this3.attrs[field] = data.result;
165 | }
166 | return data;
167 | });
168 | }
169 | }, {
170 | key: "toJson",
171 | value: function toJson() {
172 | var json = {
173 | coll: this.collection,
174 | query: this.attrs['_id'] ? { _id: this.attrs['_id'] } : {},
175 | doc: this.attrs['_id'] ? this.update : this.attrs
176 | };
177 | return json;
178 | }
179 | }, {
180 | key: "save",
181 | value: function save() {
182 | var _this4 = this;
183 |
184 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
185 |
186 | if (this.attrs['_id']) {
187 | return _data.DataStore.getInstance().updateById(this.toJson(), options).then(function (data) {
188 | if (!data.error) {
189 | _this4.attrs = data.result;
190 | }
191 | _this4.update = {};
192 | return data.result;
193 | });
194 | }
195 |
196 | return _data.DataStore.getInstance().insert(this.toJson(), options).then(function (data) {
197 | if (!data.error) {
198 | _this4.attrs = data.result;
199 | }
200 | return data.result;
201 | });
202 | }
203 | }, {
204 | key: "remove",
205 | value: function remove() {
206 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
207 |
208 | if (!this.attrs['_id']) {
209 | throw new Error("Document does't exist");
210 | }
211 | var query = new _query.SCQuery(this.collection);
212 | return query.equalTo('_id', this.attrs._id).remove(options).then(function (data) {
213 | return data;
214 | });
215 | }
216 | }], [{
217 | key: "extend",
218 | value: function extend(collName, childObject) {
219 | var obj = new SCObject(collName);
220 | for (var prop in childObject) {
221 | obj.attrs[prop] = childObject[prop];
222 | }
223 |
224 | return obj;
225 | }
226 | }]);
227 |
228 | return SCObject;
229 | }();
--------------------------------------------------------------------------------
/dist/updateOps.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCUpdateOps = exports.operators = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _utils = require('./utils');
11 |
12 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13 |
14 | var operators = {
15 | set: function set(key, value) {
16 | if (this instanceof SCUpdateOps || this.attrs['_id']) {
17 | if (key === 'createdAt' || key === 'updatedAt' || key === '_id') {
18 | return this;
19 | }
20 | if (!this.update['$set']) {
21 | this.update['$set'] = {};
22 | }
23 | this.update['$set'][key] = value;
24 |
25 | if (this.attrs) {
26 | this.attrs[key] = value;
27 | }
28 | } else {
29 | this.attrs[key] = value;
30 | }
31 |
32 | return this;
33 | },
34 | push: function push(key, value) {
35 | if (!(this instanceof SCUpdateOps)) {
36 | if (!this.attrs['_id']) {
37 | throw new Error('For a new document use the method Set');
38 | }
39 |
40 | if (!_utils.Utils.isArray(this.attrs[key])) {
41 | throw new Error('Field must by a type of array');
42 | }
43 | }
44 |
45 | if (!this.update['$push']) {
46 | this.update['$push'] = {};
47 | }
48 | this.update['$push'][key] = value;
49 |
50 | return this;
51 | },
52 | pull: function pull(key, value) {
53 | if (!(this instanceof SCUpdateOps)) {
54 | if (!this.attrs['_id']) {
55 | throw new Error('For a new document use the method Set');
56 | }
57 | }
58 |
59 | if (!this.update['$pull']) {
60 | this.update['$pull'] = {};
61 | }
62 | this.update['$pull'][key] = value;
63 |
64 | return this;
65 | },
66 | pullAll: function pullAll(key, value) {
67 | if (!(this instanceof SCUpdateOps)) {
68 | if (!this.attrs['_id']) {
69 | throw new Error('For a new document use the method Set');
70 | }
71 | }
72 |
73 | if (!_utils.Utils.isArray(value)) {
74 | throw new Error('Value must by a type of array');
75 | }
76 |
77 | if (!this.update['$pullAll']) {
78 | this.update['$pullAll'] = {};
79 | }
80 | this.update['$pullAll'][key] = value;
81 |
82 | return this;
83 | },
84 | addToSet: function addToSet(key, value) {
85 | if (!(this instanceof SCUpdateOps)) {
86 | if (!this.attrs['_id']) {
87 | throw new Error('For a new document use the method Set');
88 | }
89 | }
90 |
91 | if (!this.update['$addToSet']) {
92 | this.update['$addToSet'] = {};
93 | }
94 | this.update['$addToSet'][key] = value;
95 |
96 | return this;
97 | },
98 | pop: function pop(key, pos) {
99 | if (!(this instanceof SCUpdateOps)) {
100 | if (!this.attrs['_id']) {
101 | throw new Error('For a new document use the method Set');
102 | }
103 |
104 | if (!_utils.Utils.isArray(this.attrs[key])) {
105 | throw new Error('Field must by a type of array');
106 | }
107 | }
108 |
109 | if (pos !== 1 && pos !== -1) {
110 | throw new Error('Position must be 1 or -1');
111 | }
112 |
113 | if (!this.update['$pop']) {
114 | this.update['$pop'] = {};
115 | }
116 | this.update['$pop'][key] = pos;
117 |
118 | return this;
119 | },
120 | inc: function inc(key, value) {
121 | if (!(this instanceof SCUpdateOps)) {
122 | if (!this.attrs['_id']) {
123 | throw new Error('For a new document use the method Set');
124 | }
125 | }
126 |
127 | if (!this.update['$inc']) {
128 | this.update['$inc'] = {};
129 | }
130 | this.update['$inc'][key] = value;
131 |
132 | return this;
133 | },
134 | currentDate: function currentDate(key, type) {
135 | if (!(this instanceof SCUpdateOps)) {
136 | if (!this.attrs['_id']) {
137 | throw new Error('For a new document use the method Set');
138 | }
139 |
140 | if (type !== true && type !== 'timestamp' && type !== 'date') {
141 | throw new Error('Invalid type');
142 | }
143 | }
144 |
145 | if (!this.update['$currentDate']) {
146 | this.update['$currentDate'] = {};
147 | }
148 |
149 | if (type === 'timestamp' || type === 'date') {
150 | this.update['$currentDate'][key] = { $type: type };
151 | } else {
152 | this.update['$currentDate'][key] = type;
153 | }
154 |
155 | return this;
156 | },
157 | mul: function mul(key, value) {
158 | if (!(this instanceof SCUpdateOps)) {
159 | if (!this.attrs['_id']) {
160 | throw new Error('For a new document use the method Set');
161 | }
162 |
163 | if (!_utils.Utils.isNumber(this.attrs[key])) {
164 | throw new Error('Field must by a type of number');
165 | }
166 | }
167 |
168 | if (!_utils.Utils.isNumber(value)) {
169 | throw new Error('Value must by a type of number');
170 | }
171 |
172 | if (!this.update['$mul']) {
173 | this.update['$mul'] = {};
174 | }
175 |
176 | this.update['$mul'][key] = value;
177 |
178 | return this;
179 | },
180 | min: function min(key, value) {
181 | if (!(this instanceof SCUpdateOps)) {
182 | if (!this.attrs['_id']) {
183 | throw new Error('For a new document use the method Set');
184 | }
185 |
186 | if (!_utils.Utils.isNumber(this.attrs[key])) {
187 | throw new Error('Field must by a type of number');
188 | }
189 | }
190 |
191 | if (!_utils.Utils.isNumber(value)) {
192 | throw new Error('Value must by a type of number');
193 | }
194 |
195 | if (!this.update['$min']) {
196 | this.update['$min'] = {};
197 | }
198 |
199 | this.update['$min'][key] = value;
200 |
201 | return this;
202 | },
203 | max: function max(key, value) {
204 | if (!(this instanceof SCUpdateOps)) {
205 | if (!this.attrs['_id']) {
206 | throw new Error('For a new document use the method Set');
207 | }
208 |
209 | if (!_utils.Utils.isNumber(this.attrs[key])) {
210 | throw new Error('Field must by a type of number');
211 | }
212 | }
213 |
214 | if (!_utils.Utils.isNumber(value)) {
215 | throw new Error('Value must by a type of number');
216 | }
217 |
218 | if (!this.update['$max']) {
219 | this.update['$max'] = {};
220 | }
221 |
222 | this.update['$max'][key] = value;
223 |
224 | return this;
225 | }
226 | };
227 |
228 | var SCUpdateOps = function () {
229 | function SCUpdateOps() {
230 | _classCallCheck(this, SCUpdateOps);
231 |
232 | this.update = {};
233 | for (var prop in operators) {
234 | this[prop] = operators[prop];
235 | }
236 | }
237 |
238 | _createClass(SCUpdateOps, [{
239 | key: 'toJson',
240 | value: function toJson() {
241 | var json = this.update;
242 | return json;
243 | }
244 | }]);
245 |
246 | return SCUpdateOps;
247 | }();
248 |
249 | exports.operators = operators;
250 | exports.SCUpdateOps = SCUpdateOps;
--------------------------------------------------------------------------------
/dist/stores/networkStore.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.Network = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _protocol = require('../protocol');
11 |
12 | var _httpRequest = require('../httpRequest');
13 |
14 | var _utils = require('../utils');
15 |
16 | var _bson = require('../bson');
17 |
18 | var _client = require('../client');
19 |
20 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
21 |
22 | var Network = exports.Network = function () {
23 | function Network() {
24 | _classCallCheck(this, Network);
25 | }
26 |
27 | _createClass(Network, [{
28 | key: 'find',
29 | value: function find(query, options) {
30 | var protocolOpts = {
31 | url: _client.SDKOptions.FIND_URL
32 | };
33 |
34 | var protocol = _protocol.DataProtocol.init(query, null, protocolOpts);
35 | var request = new _httpRequest.HttpRequest(protocol);
36 | var promise = request.execute().then(function (data) {
37 | return JSON.parse(data);
38 | }).then(function (response) {
39 | if (response.error) {
40 | return Promise.reject(response);
41 | }
42 |
43 | var base64Decoded = new Buffer(response.result, 'base64');
44 | var deserializedBson = (0, _bson.deserializeFast)(base64Decoded, 0, true);
45 |
46 | return {
47 | error: false,
48 | limit: response.limit,
49 | skip: response.skip,
50 | result: deserializedBson.slice()
51 | };
52 | });
53 |
54 | return _utils.Utils.wrapCallbacks(promise, options);
55 | }
56 | }, {
57 | key: 'count',
58 | value: function count(query, options) {
59 | var protocolOpts = {
60 | url: _client.SDKOptions.COUNT_URL
61 | };
62 |
63 | var protocol = _protocol.DataProtocol.init(query, null, protocolOpts);
64 | var request = new _httpRequest.HttpRequest(protocol);
65 | var promise = request.execute().then(function (data) {
66 | return JSON.parse(data);
67 | }).then(function (response) {
68 | if (response.error) {
69 | return Promise.reject(response);
70 | }
71 |
72 | return response;
73 | });
74 |
75 | return _utils.Utils.wrapCallbacks(promise, options);
76 | }
77 | }, {
78 | key: 'update',
79 | value: function update(query, doc, options) {
80 | var protocolOpts = {
81 | url: _client.SDKOptions.UPDATE_URL
82 | };
83 |
84 | var protocol = _protocol.DataProtocol.init(query, doc, protocolOpts);
85 | var request = new _httpRequest.HttpRequest(protocol);
86 | var promise = request.execute().then(function (data) {
87 | return JSON.parse(data);
88 | }).then(function (response) {
89 | if (response.error) {
90 | return Promise.reject(response);
91 | }
92 |
93 | return response;
94 | });
95 |
96 | return _utils.Utils.wrapCallbacks(promise, options);
97 | }
98 | }, {
99 | key: 'updateById',
100 | value: function updateById(query, options) {
101 | var protocolOpts = {
102 | url: _client.SDKOptions.UPDATE_BY_ID_URL
103 | };
104 |
105 | var protocol = _protocol.DataProtocol.init(query, null, protocolOpts);
106 | var request = new _httpRequest.HttpRequest(protocol);
107 | var promise = request.execute().then(function (data) {
108 | return JSON.parse(data);
109 | }).then(function (response) {
110 | if (response.error) {
111 | return Promise.reject(response);
112 | }
113 |
114 | return response;
115 | });
116 |
117 | return _utils.Utils.wrapCallbacks(promise, options);
118 | }
119 | }, {
120 | key: 'remove',
121 | value: function remove(query, options) {
122 | var protocolOpts = {
123 | url: _client.SDKOptions.REMOVE_URL
124 | };
125 |
126 | var protocol = _protocol.DataProtocol.init(query, null, protocolOpts);
127 | var request = new _httpRequest.HttpRequest(protocol);
128 | var promise = request.execute().then(function (data) {
129 | return JSON.parse(data);
130 | }).then(function (response) {
131 | if (response.error) {
132 | return Promise.reject(response);
133 | }
134 |
135 | return response.result;
136 | });
137 |
138 | return _utils.Utils.wrapCallbacks(promise, options);
139 | }
140 | }, {
141 | key: 'insert',
142 | value: function insert(query, options) {
143 | var protocolOpts = {
144 | url: _client.SDKOptions.INSERT_URL
145 | };
146 |
147 | var protocol = _protocol.DataProtocol.init(query, null, protocolOpts);
148 | var request = new _httpRequest.HttpRequest(protocol);
149 | var promise = request.execute().then(function (data) {
150 | return JSON.parse(data);
151 | }).then(function (response) {
152 | if (response.error) {
153 | return Promise.reject(response);
154 | }
155 |
156 | return response;
157 | });
158 |
159 | return _utils.Utils.wrapCallbacks(promise, options);
160 | }
161 | }, {
162 | key: 'uploadFile',
163 | value: function uploadFile(params, options) {
164 | var protocolOpts = {
165 | url: _client.SDKOptions.UPLOAD_URL
166 | };
167 | var client = _client.Client.getInstance();
168 | var protocol = _protocol.DataProtocol.init(params, null, protocolOpts);
169 |
170 | protocol.setAccessKey('acc', client.masterKey || client.fileKey);
171 |
172 | var request = new _httpRequest.HttpRequest(protocol);
173 | var promise = request.execute(options).then(function (data) {
174 | return JSON.parse(data);
175 | }).then(function (response) {
176 | if (response.error) {
177 | return Promise.reject(response);
178 | }
179 |
180 | return response;
181 | });
182 |
183 | return _utils.Utils.wrapCallbacks(promise, options);
184 | }
185 | }, {
186 | key: 'removeFile',
187 | value: function removeFile(params, options) {
188 | var protocolOpts = {
189 | url: _client.SDKOptions.REMOVE_FILE_URL
190 | };
191 |
192 | var client = _client.Client.getInstance();
193 | var protocol = _protocol.DataProtocol.init(params, null, protocolOpts);
194 |
195 | protocol.setAccessKey('acc', client.masterKey || client.fileKey);
196 | var request = new _httpRequest.HttpRequest(protocol);
197 | var promise = request.execute().then(function (data) {
198 | return JSON.parse(data);
199 | }).then(function (response) {
200 | if (response.error) {
201 | return Promise.reject(response);
202 | }
203 |
204 | return response;
205 | });
206 |
207 | return _utils.Utils.wrapCallbacks(promise, options);
208 | }
209 | }]);
210 |
211 | return Network;
212 | }();
--------------------------------------------------------------------------------
/dist/instance.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCInstance = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _utils = require('./utils');
11 |
12 | var _httpRequest = require('./httpRequest');
13 |
14 | var _protocol = require('./protocol');
15 |
16 | var _client = require('./client');
17 |
18 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
19 |
20 | var SCInstance = exports.SCInstance = function () {
21 | function SCInstance(data) {
22 | _classCallCheck(this, SCInstance);
23 |
24 | this._extend(data);
25 | }
26 |
27 | _createClass(SCInstance, [{
28 | key: '_extend',
29 | value: function _extend(data) {
30 | for (var it in data) {
31 | this[it] = data[it];
32 | }
33 | }
34 | }, {
35 | key: 'save',
36 | value: function save() {
37 | var _this = this;
38 |
39 | var callbacks = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
40 |
41 | var protocolOpts = !this.id ? {
42 | url: _client.SDKOptions.CREATE_INSTANCE_URL
43 | } : {
44 | url: _client.SDKOptions.UPDATE_INSTANCE_URL
45 | };
46 |
47 | var protocol = _protocol.Protocol.init(protocolOpts);
48 |
49 | protocol.setData({
50 | id: this.id || null,
51 | name: this.name,
52 | autorun: this.autorun || []
53 | });
54 |
55 | var request = new _httpRequest.HttpRequest(protocol);
56 | var promise = request.execute().then(function (data) {
57 | return JSON.parse(data);
58 | }).then(function (response) {
59 | if (response.error) {
60 | return Promise.reject(response);
61 | }
62 | _this._extend(response.result);
63 | return _this;
64 | });
65 | return _utils.Utils.wrapCallbacks(promise, callbacks);
66 | }
67 | }, {
68 | key: 'remove',
69 | value: function remove() {
70 | var callbacks = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
71 |
72 | var protocolOpts = {
73 | url: _client.SDKOptions.REMOVE_INSTANCE_URL
74 | };
75 | var protocol = _protocol.Protocol.init(protocolOpts);
76 | protocol.setData({
77 | id: this.id
78 | });
79 |
80 | var request = new _httpRequest.HttpRequest(protocol);
81 | var promise = request.execute().then(function (data) {
82 | return JSON.parse(data);
83 | }).then(function (response) {
84 | if (response.error) {
85 | return Promise.reject(response);
86 | }
87 | return response.result;
88 | });
89 | return _utils.Utils.wrapCallbacks(promise, callbacks);
90 | }
91 | }, {
92 | key: 'run',
93 | value: function run() {
94 | var callbacks = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
95 |
96 | var protocolOpts = {
97 | url: _client.SDKOptions.RUN_INSTANCE_URL
98 | };
99 | var protocol = _protocol.Protocol.init(protocolOpts);
100 | protocol.setData({
101 | id: this.id
102 | });
103 |
104 | var request = new _httpRequest.HttpRequest(protocol);
105 | var promise = request.execute().then(function (data) {
106 | return JSON.parse(data);
107 | }).then(function (response) {
108 | if (response.error) {
109 | return Promise.reject(response);
110 | }
111 |
112 | return response.result;
113 | });
114 | return _utils.Utils.wrapCallbacks(promise, callbacks);
115 | }
116 | }, {
117 | key: 'stop',
118 | value: function stop() {
119 | var callbacks = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
120 |
121 | var protocolOpts = {
122 | url: _client.SDKOptions.STOP_INSTANCE_URL
123 | };
124 | var protocol = _protocol.Protocol.init(protocolOpts);
125 | protocol.setData({
126 | id: this.id
127 | });
128 |
129 | var request = new _httpRequest.HttpRequest(protocol);
130 | var promise = request.execute().then(function (data) {
131 | return JSON.parse(data);
132 | }).then(function (response) {
133 | if (response.error) {
134 | return Promise.reject(response);
135 | }
136 |
137 | return response.result;
138 | });
139 | return _utils.Utils.wrapCallbacks(promise, callbacks);
140 | }
141 | }, {
142 | key: 'runScript',
143 | value: function runScript(path) {
144 | var pool = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
145 | var callbacks = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
146 |
147 | var protocolOpts = {
148 | url: _client.SDKOptions.RUN_SCRIPT_INSTANCE_URL
149 | };
150 | var protocol = _protocol.Protocol.init(protocolOpts);
151 | protocol.setData({
152 | id: this.id,
153 | path: path,
154 | pool: pool
155 | });
156 |
157 | var request = new _httpRequest.HttpRequest(protocol);
158 | var promise = request.execute().then(function (data) {
159 | return JSON.parse(data);
160 | }).then(function (response) {
161 | if (response.error) {
162 | return Promise.reject(response);
163 | }
164 |
165 | return response.result;
166 | });
167 | return _utils.Utils.wrapCallbacks(promise, callbacks);
168 | }
169 | }, {
170 | key: 'killScript',
171 | value: function killScript(pid) {
172 | var callbacks = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
173 |
174 | var protocolOpts = {
175 | url: _client.SDKOptions.KILL_SCRIPT_INSTANCE_URL
176 | };
177 | var protocol = _protocol.Protocol.init(protocolOpts);
178 | protocol.setData({
179 | id: this.id,
180 | pid: pid
181 | });
182 |
183 | var request = new _httpRequest.HttpRequest(protocol);
184 | var promise = request.execute().then(function (data) {
185 | return JSON.parse(data);
186 | }).then(function (response) {
187 | if (response.error) {
188 | return Promise.reject(response);
189 | }
190 |
191 | return response.result;
192 | });
193 | return _utils.Utils.wrapCallbacks(promise, callbacks);
194 | }
195 | }, {
196 | key: 'getScripts',
197 | value: function getScripts() {
198 | var callbacks = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
199 |
200 | var protocolOpts = {
201 | url: _client.SDKOptions.SCRIPTS_INSTANCE_URL
202 | };
203 | var protocol = _protocol.Protocol.init(protocolOpts);
204 | protocol.setData({
205 | id: this.id
206 | });
207 |
208 | var request = new _httpRequest.HttpRequest(protocol);
209 | var promise = request.execute().then(function (data) {
210 | return JSON.parse(data);
211 | }).then(function (response) {
212 | if (response.error) {
213 | return Promise.reject(response);
214 | }
215 |
216 | return response.result;
217 | });
218 | return _utils.Utils.wrapCallbacks(promise, callbacks);
219 | }
220 | }]);
221 |
222 | return SCInstance;
223 | }();
--------------------------------------------------------------------------------
/dist/protocol.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.CloudFileProtocol = exports.BotProtocol = exports.CloudCodeProtocol = exports.MessengerProtocol = exports.UserProtocol = exports.DataProtocol = exports.Protocol = undefined;
7 |
8 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9 |
10 | var _client = require('./client');
11 |
12 | function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
13 |
14 | function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
15 |
16 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17 |
18 | var Protocol = exports.Protocol = function () {
19 | function Protocol(client, opts) {
20 | _classCallCheck(this, Protocol);
21 |
22 | this.method = 'POST';
23 | this.host = client.get('HOST');
24 | this.port = client.get('PORT');
25 | this.path = opts.url;
26 | this.data = {
27 | app: client.applicationID,
28 | cli: client.clientKey,
29 | acc: client.masterKey
30 | };
31 | //sess: client.sessionId
32 | this.headers = {
33 | 'Content-Type': 'application/json'
34 | };
35 |
36 | if (client.sessionId) {
37 | this.headers['Authorization'] = 'Bearer ' + client.sessionId;
38 | }
39 |
40 | this.timeout = opts.timeout || client.get('TIMEOUT');
41 | }
42 |
43 | _createClass(Protocol, [{
44 | key: 'setAccessKey',
45 | value: function setAccessKey(key, value) {
46 | this.data[key] = value;
47 | return this;
48 | }
49 | }, {
50 | key: 'setData',
51 | value: function setData(data) {
52 | for (var prop in data) {
53 | Object.defineProperty(this.data, prop, {
54 | value: data[prop],
55 | enumerable: true,
56 | writable: true,
57 | configurable: true
58 | });
59 | }
60 |
61 | return this;
62 | }
63 | }, {
64 | key: 'setDoc',
65 | value: function setDoc(doc) {
66 | if (doc) {
67 | this.data.doc = doc;
68 | }
69 |
70 | return this;
71 | }
72 | }, {
73 | key: 'setIndex',
74 | value: function setIndex(index) {
75 | this.data.index = index;
76 | }
77 | }, {
78 | key: 'setField',
79 | value: function setField(field) {
80 | this.data.collField = field;
81 | }
82 | }, {
83 | key: 'setPath',
84 | value: function setPath(path) {
85 | this.data.path = path;
86 | }
87 | }, {
88 | key: 'setTriggers',
89 | value: function setTriggers(triggers) {
90 | this.data.triggers = triggers;
91 | }
92 | }, {
93 | key: 'setColl',
94 | value: function setColl(coll) {
95 | this.data.coll = coll;
96 |
97 | return this;
98 | }
99 | }, {
100 | key: 'setCollection',
101 | value: function setCollection(coll) {
102 | this.data.collection = coll;
103 |
104 | return this;
105 | }
106 | }, {
107 | key: 'toJson',
108 | value: function toJson() {
109 | var Json = {};
110 |
111 | for (var prop in this) {
112 | if (prop === 'data') {
113 | Json[prop] = JSON.stringify(this[prop]);
114 | continue;
115 | }
116 | Json[prop] = this[prop];
117 | }
118 |
119 | return Json;
120 | }
121 | }], [{
122 | key: 'init',
123 | value: function init(opts) {
124 | var client = _client.Client.getInstance();
125 | var protocol = new Protocol(client, opts);
126 |
127 | return protocol;
128 | }
129 | }]);
130 |
131 | return Protocol;
132 | }();
133 |
134 | var DataProtocol = exports.DataProtocol = function (_Protocol) {
135 | _inherits(DataProtocol, _Protocol);
136 |
137 | function DataProtocol(client, opts) {
138 | _classCallCheck(this, DataProtocol);
139 |
140 | return _possibleConstructorReturn(this, Object.getPrototypeOf(DataProtocol).call(this, client, opts));
141 | }
142 |
143 | _createClass(DataProtocol, null, [{
144 | key: 'init',
145 | value: function init() {
146 | var query = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
147 | var doc = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
148 | var opts = arguments[2];
149 |
150 | var client = _client.Client.getInstance();
151 | var protocol = new DataProtocol(client, opts);
152 | protocol.setData(query);
153 | protocol.setDoc(doc);
154 |
155 | return protocol;
156 | }
157 | }]);
158 |
159 | return DataProtocol;
160 | }(Protocol);
161 |
162 | var UserProtocol = exports.UserProtocol = function (_Protocol2) {
163 | _inherits(UserProtocol, _Protocol2);
164 |
165 | function UserProtocol(client, opts) {
166 | _classCallCheck(this, UserProtocol);
167 |
168 | return _possibleConstructorReturn(this, Object.getPrototypeOf(UserProtocol).call(this, client, opts));
169 | }
170 |
171 | _createClass(UserProtocol, null, [{
172 | key: 'init',
173 | value: function init(data, doc, opts) {
174 | var client = _client.Client.getInstance();
175 | var protocol = new UserProtocol(client, opts);
176 | protocol.setData(data);
177 | protocol.setDoc(doc);
178 |
179 | return protocol;
180 | }
181 | }]);
182 |
183 | return UserProtocol;
184 | }(Protocol);
185 |
186 | var MessengerProtocol = exports.MessengerProtocol = function (_Protocol3) {
187 | _inherits(MessengerProtocol, _Protocol3);
188 |
189 | function MessengerProtocol(client, options) {
190 | _classCallCheck(this, MessengerProtocol);
191 |
192 | return _possibleConstructorReturn(this, Object.getPrototypeOf(MessengerProtocol).call(this, client, options));
193 | }
194 |
195 | _createClass(MessengerProtocol, null, [{
196 | key: 'init',
197 | value: function init(data, options) {
198 | var client = _client.Client.getInstance();
199 | var protocol = new MessengerProtocol(client, options);
200 | protocol.setData(data);
201 | protocol.setAccessKey('acc', client.masterKey || client.messageKey);
202 | return protocol;
203 | }
204 | }]);
205 |
206 | return MessengerProtocol;
207 | }(Protocol);
208 |
209 | var CloudCodeProtocol = exports.CloudCodeProtocol = function (_Protocol4) {
210 | _inherits(CloudCodeProtocol, _Protocol4);
211 |
212 | function CloudCodeProtocol(client, options) {
213 | _classCallCheck(this, CloudCodeProtocol);
214 |
215 | return _possibleConstructorReturn(this, Object.getPrototypeOf(CloudCodeProtocol).call(this, client, options));
216 | }
217 |
218 | _createClass(CloudCodeProtocol, null, [{
219 | key: 'init',
220 | value: function init(data, options) {
221 | var client = _client.Client.getInstance();
222 | var protocol = new CloudCodeProtocol(client, options);
223 | protocol.setData(data);
224 | protocol.setAccessKey('acc', client.masterKey || client.scriptKey);
225 | return protocol;
226 | }
227 | }]);
228 |
229 | return CloudCodeProtocol;
230 | }(Protocol);
231 |
232 | var BotProtocol = exports.BotProtocol = function () {
233 | function BotProtocol(botId, client, opts) {
234 | _classCallCheck(this, BotProtocol);
235 |
236 | this.method = 'POST';
237 | this.host = client.get('BOT_HOST');
238 | this.port = client.get('PORT');
239 | this.path = client.get('BOT_URL') + botId + '/response';
240 | this.data = {};
241 | this.headers = {
242 | 'Content-Type': 'application/json'
243 | };
244 | this.timeout = opts.timeout || client.get('TIMEOUT');
245 | }
246 |
247 | _createClass(BotProtocol, [{
248 | key: 'setData',
249 | value: function setData(data) {
250 | for (var prop in data) {
251 | Object.defineProperty(this.data, prop, {
252 | value: data[prop],
253 | enumerable: true,
254 | writable: true,
255 | configurable: true
256 | });
257 | }
258 | }
259 | }, {
260 | key: 'toJson',
261 | value: function toJson() {
262 | var Json = {};
263 |
264 | for (var prop in this) {
265 | if (prop === 'data') {
266 | Json[prop] = JSON.stringify(this[prop]);
267 | continue;
268 | }
269 | Json[prop] = this[prop];
270 | }
271 |
272 | return Json;
273 | }
274 | }], [{
275 | key: 'init',
276 | value: function init(botId) {
277 | var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
278 |
279 | var client = _client.Client.getInstance();
280 | var protocol = new BotProtocol(botId, client, options);
281 |
282 | return protocol;
283 | }
284 | }]);
285 |
286 | return BotProtocol;
287 | }();
288 |
289 | var CloudFileProtocol = exports.CloudFileProtocol = function (_Protocol5) {
290 | _inherits(CloudFileProtocol, _Protocol5);
291 |
292 | function CloudFileProtocol() {
293 | _classCallCheck(this, CloudFileProtocol);
294 |
295 | var _this5 = _possibleConstructorReturn(this, Object.getPrototypeOf(CloudFileProtocol).call(this));
296 |
297 | _this5.docId = "";
298 | _this5.field = "";
299 | return _this5;
300 | }
301 |
302 | return CloudFileProtocol;
303 | }(Protocol);
--------------------------------------------------------------------------------
/dist/query.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 | exports.SCQuery = undefined;
7 |
8 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
9 |
10 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
11 |
12 | var _utils = require("./utils");
13 |
14 | var _data = require("./stores/data");
15 |
16 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17 |
18 | var SCQuery = function () {
19 | function SCQuery(collName) {
20 | _classCallCheck(this, SCQuery);
21 |
22 | if (typeof collName !== 'string') {
23 | throw new Error('Collection name must be a type of string');
24 | }
25 | this._collection = collName;
26 | this._fields = [];
27 | this._filter = {};
28 | this._sort = {};
29 | this._limit = 100;
30 | this._skip = 0;
31 | }
32 |
33 | _createClass(SCQuery, [{
34 | key: "_addFilter",
35 | value: function _addFilter(field, condition, values) {
36 | if (!_utils.Utils.isObject(this._filter[field])) {
37 | this._filter[field] = {};
38 | }
39 |
40 | if ((typeof condition === "undefined" ? "undefined" : _typeof(condition)) === 'object') {
41 | this._filter[field] = condition;
42 | return this;
43 | }
44 |
45 | this._filter[field][condition] = values;
46 | return this;
47 | }
48 | }, {
49 | key: "find",
50 | value: function find() {
51 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
52 |
53 | //TODO: Следует возвращать массив SC.Object вместо сырых данных
54 | return _data.DataStore.getInstance().find(this.toJson(), options);
55 | }
56 |
57 | // Не следует использовать для больших коллекций
58 |
59 | }, {
60 | key: "findAll",
61 | value: function findAll() {
62 | var _this = this;
63 |
64 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
65 |
66 | var result = [];
67 | return _utils.Utils.promiseWhile(function (res) {
68 | if (!res) {
69 | return true;
70 | }
71 |
72 | if (!res.result.length) {
73 | return false;
74 | }
75 |
76 | result = result.concat(res.result);
77 | _this.skip(_this._skip + _this._limit);
78 |
79 | return true;
80 | }, function () {
81 | return _data.DataStore.getInstance().find(_this.toJson(), options);
82 | }).then(function (res) {
83 | return result;
84 | });
85 | }
86 | }, {
87 | key: "count",
88 | value: function count() {
89 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
90 |
91 | return _data.DataStore.getInstance().count(this.toJson(), options);
92 | }
93 | }, {
94 | key: "update",
95 | value: function update(object) {
96 | var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
97 |
98 | return _data.DataStore.getInstance().update(this.toJson(), object.toJson(), options);
99 | }
100 | }, {
101 | key: "remove",
102 | value: function remove() {
103 | var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
104 |
105 | return _data.DataStore.getInstance().remove(this.toJson(), options);
106 | }
107 | }, {
108 | key: "reset",
109 | value: function reset() {
110 | this._filter = {};
111 | this.fields = [];
112 |
113 | return this;
114 | }
115 | }, {
116 | key: "equalTo",
117 | value: function equalTo(field, value) {
118 | this._filter[field] = value;
119 | return this;
120 | }
121 | }, {
122 | key: "notEqualTo",
123 | value: function notEqualTo(field, value) {
124 | return this._addFilter(field, "$ne", value);
125 | }
126 | }, {
127 | key: "containedIn",
128 | value: function containedIn(field, value) {
129 | if (!_utils.Utils.isArray(value)) {
130 | throw new Error('Value must be of type: Array');
131 | }
132 |
133 | return this._addFilter(field, '$in', value);
134 | }
135 | }, {
136 | key: "containsAll",
137 | value: function containsAll(field, value) {
138 | if (!_utils.Utils.isArray(value)) {
139 | throw new Error('Value must be of type: Array');
140 | }
141 |
142 | return this._addFilter(field, '$all', value);
143 | }
144 | }, {
145 | key: "notContainedIn",
146 | value: function notContainedIn(field, value) {
147 | if (!_utils.Utils.isArray(value)) {
148 | throw new Error('Value must be of type: Array');
149 | }
150 |
151 | return this._addFilter(field, '$nin', value);
152 | }
153 | }, {
154 | key: "greaterThan",
155 | value: function greaterThan(field, value) {
156 | return this._addFilter(field, '$gt', value);
157 | }
158 | }, {
159 | key: "greaterThanOrEqualTo",
160 | value: function greaterThanOrEqualTo(field, value) {
161 | return this._addFilter(field, '$gte', value);
162 | }
163 | }, {
164 | key: "lessThan",
165 | value: function lessThan(field, value) {
166 | return this._addFilter(field, '$lt', value);
167 | }
168 | }, {
169 | key: "lessThanOrEqualTo",
170 | value: function lessThanOrEqualTo(field, value) {
171 | return this._addFilter(field, '$lte', value);
172 | }
173 | }, {
174 | key: "exists",
175 | value: function exists(field) {
176 | return this._addFilter(field, '$exists', true);
177 | }
178 | }, {
179 | key: "doesNotExist",
180 | value: function doesNotExist(field) {
181 | return this._addFilter(field, '$exists', false);
182 | }
183 | }, {
184 | key: "contains",
185 | value: function contains(field, value, opts) {
186 | if (opts) {
187 | return this._addFilter(field, { $regex: value, $options: opts });
188 | }
189 |
190 | return this._addFilter(field, '$regex', value);
191 | }
192 | }, {
193 | key: "startsWith",
194 | value: function startsWith(field, value, opts) {
195 | if (typeof value !== 'string') {
196 | throw new Error("Value must be a string");
197 | }
198 |
199 | if (opts) {
200 | return this._addFilter(field, { $regex: '^' + value, $options: opts });
201 | }
202 |
203 | return this._addFilter(field, '$regex', '^' + value);
204 | }
205 | }, {
206 | key: "endsWith",
207 | value: function endsWith(field, value, opts) {
208 | if (typeof value !== 'string') {
209 | throw new Error("Value must be a string");
210 | }
211 |
212 | if (opts) {
213 | return this._addFilter(field, { $regex: value + '$', $options: opts });
214 | }
215 |
216 | return this._addFilter(field, '$regex', value + '$');
217 | }
218 | }, {
219 | key: "limit",
220 | value: function limit(_limit) {
221 | if (!_utils.Utils.isNumber(_limit) || _limit < 0) {
222 | throw new Error("Limit must be a positive number");
223 | }
224 |
225 | this._limit = _limit;
226 |
227 | return this;
228 | }
229 | }, {
230 | key: "skip",
231 | value: function skip(_skip) {
232 | if (!_utils.Utils.isNumber(_skip) || _skip < 0) {
233 | throw new Error("Skip must be a positive number");
234 | }
235 |
236 | this._skip = _skip;
237 |
238 | return this;
239 | }
240 | }, {
241 | key: "page",
242 | value: function page(_page) {
243 | if (!_utils.Utils.isNumber(_page) || _page < 0) {
244 | throw new Error("Page must be a positive number");
245 | }
246 |
247 | this._skip = (_page - 1) * this._limit;
248 |
249 | return this;
250 | }
251 | }, {
252 | key: "ascending",
253 | value: function ascending(field) {
254 | this._sort[field] = 1;
255 |
256 | return this;
257 | }
258 | }, {
259 | key: "descending",
260 | value: function descending(field) {
261 | this._sort[field] = -1;
262 |
263 | return this;
264 | }
265 | }, {
266 | key: "or",
267 | value: function or(query) {
268 | if (!(query instanceof SCQuery)) {
269 | throw new Error('Invalid type of Query');
270 | }
271 |
272 | if (!this._filter['$or']) {
273 | this._filter['$or'] = [];
274 | }
275 |
276 | this._filter['$or'].push(query.toJson().query);
277 |
278 | return this;
279 | }
280 | }, {
281 | key: "and",
282 | value: function and(query) {
283 | if (!(query instanceof SCQuery)) {
284 | throw new Error('Invalid type of Query');
285 | }
286 |
287 | if (!this._filter['$and']) {
288 | this._filter['$and'] = [];
289 | }
290 |
291 | this._filter['$and'].push(query.toJson().query);
292 |
293 | return this;
294 | }
295 | }, {
296 | key: "select",
297 | value: function select() {
298 | this._fields = [];
299 | var ln = arguments.length;
300 |
301 | for (var i = 0; i < ln; i++) {
302 | this._fields.push(arguments[i]);
303 | }
304 |
305 | return this;
306 | }
307 | }, {
308 | key: "raw",
309 | value: function raw(filter) {
310 | if (!_utils.Utils.isObject(filter)) {
311 | throw new Error('Filter must be a object');
312 | }
313 | this._filter = filter;
314 |
315 | return this;
316 | }
317 | }, {
318 | key: "toJson",
319 | value: function toJson() {
320 | var json = {
321 | coll: this._collection,
322 | limit: this._limit,
323 | skip: this._skip,
324 | query: this._filter,
325 | sort: this._sort,
326 | fields: this._fields
327 | };
328 |
329 | return json;
330 | }
331 | }]);
332 |
333 | return SCQuery;
334 | }();
335 |
336 | exports.SCQuery = SCQuery;
--------------------------------------------------------------------------------
/src/objectid.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Machine id.
3 | *
4 | * Create a random 3-byte value (i.e. unique for this
5 | * process). Other drivers use a md5 of the machine id here, but
6 | * that would mean an asyc call to gethostname, so we don't bother.
7 | * @ignore
8 | */
9 | var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);
10 |
11 | // Regular expression that checks for hex value
12 | var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
13 | var hasBufferType = false;
14 |
15 | // Check if buffer exists
16 | try {
17 | if(Buffer && Buffer.from) hasBufferType = true;
18 | } catch(err) {};
19 |
20 | /**
21 | * Create a new ObjectID instance
22 | *
23 | * @class
24 | * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
25 | * @property {number} generationTime The generation time of this ObjectId instance
26 | * @return {ObjectID} instance of ObjectID.
27 | */
28 | var ObjectID = function ObjectID(id) {
29 | // Duck-typing to support ObjectId from different npm packages
30 | if(id instanceof ObjectID) return id;
31 | if(!(this instanceof ObjectID)) return new ObjectID(id);
32 |
33 | this._bsontype = 'ObjectID';
34 |
35 | // The most common usecase (blank id, new objectId instance)
36 | if(id == null || typeof id == 'number') {
37 | // Generate a new id
38 | this.id = this.generate(id);
39 | // If we are caching the hex string
40 | if(ObjectID.cacheHexString) this.__id = this.toString('hex');
41 | // Return the object
42 | return;
43 | }
44 |
45 | // Check if the passed in id is valid
46 | var valid = ObjectID.isValid(id);
47 |
48 | // Throw an error if it's not a valid setup
49 | if(!valid && id != null){
50 | throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
51 | } else if(valid && typeof id == 'string' && id.length == 24 && hasBufferType) {
52 | return new ObjectID(new Buffer(id, 'hex'));
53 | } else if(valid && typeof id == 'string' && id.length == 24) {
54 | return ObjectID.createFromHexString(id);
55 | } else if(id != null && id.length === 12) {
56 | // assume 12 byte string
57 | this.id = id;
58 | } else if(id != null && id.toHexString) {
59 | // Duck-typing to support ObjectId from different npm packages
60 | return id;
61 | } else {
62 | throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
63 | }
64 |
65 | if(ObjectID.cacheHexString) this.__id = this.toString('hex');
66 | };
67 |
68 | // Allow usage of ObjectId as well as ObjectID
69 | var ObjectId = ObjectID;
70 |
71 | // Precomputed hex table enables speedy hex string conversion
72 | var hexTable = [];
73 | for (var i = 0; i < 256; i++) {
74 | hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
75 | }
76 |
77 | /**
78 | * Return the ObjectID id as a 24 byte hex string representation
79 | *
80 | * @method
81 | * @return {string} return the 24 byte hex string representation.
82 | */
83 | ObjectID.prototype.toHexString = function() {
84 | if(ObjectID.cacheHexString && this.__id) return this.__id;
85 |
86 | var hexString = '';
87 | if(!this.id || !this.id.length) {
88 | throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
89 | }
90 |
91 | if(this.id instanceof _Buffer) {
92 | hexString = convertToHex(this.id);
93 | if(ObjectID.cacheHexString) this.__id = hexString;
94 | return hexString;
95 | }
96 |
97 | for (var i = 0; i < this.id.length; i++) {
98 | hexString += hexTable[this.id.charCodeAt(i)];
99 | }
100 |
101 | if(ObjectID.cacheHexString) this.__id = hexString;
102 | return hexString;
103 | };
104 |
105 | /**
106 | * Update the ObjectID index used in generating new ObjectID's on the driver
107 | *
108 | * @method
109 | * @return {number} returns next index value.
110 | * @ignore
111 | */
112 | ObjectID.prototype.get_inc = function() {
113 | return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF;
114 | };
115 |
116 | /**
117 | * Update the ObjectID index used in generating new ObjectID's on the driver
118 | *
119 | * @method
120 | * @return {number} returns next index value.
121 | * @ignore
122 | */
123 | ObjectID.prototype.getInc = function() {
124 | return this.get_inc();
125 | };
126 |
127 | /**
128 | * Generate a 12 byte id buffer used in ObjectID's
129 | *
130 | * @method
131 | * @param {number} [time] optional parameter allowing to pass in a second based timestamp.
132 | * @return {Buffer} return the 12 byte id buffer string.
133 | */
134 | ObjectID.prototype.generate = function(time) {
135 | if ('number' != typeof time) {
136 | time = ~~(Date.now()/1000);
137 | }
138 |
139 | // Use pid
140 | var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;
141 | var inc = this.get_inc();
142 | // Buffer used
143 | var buffer = new Buffer(12);
144 | // Encode time
145 | buffer[3] = time & 0xff;
146 | buffer[2] = (time >> 8) & 0xff;
147 | buffer[1] = (time >> 16) & 0xff;
148 | buffer[0] = (time >> 24) & 0xff;
149 | // Encode machine
150 | buffer[6] = MACHINE_ID & 0xff;
151 | buffer[5] = (MACHINE_ID >> 8) & 0xff;
152 | buffer[4] = (MACHINE_ID >> 16) & 0xff;
153 | // Encode pid
154 | buffer[8] = pid & 0xff;
155 | buffer[7] = (pid >> 8) & 0xff;
156 | // Encode index
157 | buffer[11] = inc & 0xff;
158 | buffer[10] = (inc >> 8) & 0xff;
159 | buffer[9] = (inc >> 16) & 0xff;
160 | // Return the buffer
161 | return buffer;
162 | };
163 |
164 | /**
165 | * Converts the id into a 24 byte hex string for printing
166 | *
167 | * @param {String} format The Buffer toString format parameter.
168 | * @return {String} return the 24 byte hex string representation.
169 | * @ignore
170 | */
171 | ObjectID.prototype.toString = function(format) {
172 | // Is the id a buffer then use the buffer toString method to return the format
173 | if(this.id && this.id.copy) {
174 | return this.id.toString(typeof format === 'string' ? format : 'hex');
175 | }
176 |
177 | // if(this.buffer )
178 | return this.toHexString();
179 | };
180 |
181 | /**
182 | * Converts to a string representation of this Id.
183 | *
184 | * @return {String} return the 24 byte hex string representation.
185 | * @ignore
186 | */
187 | ObjectID.prototype.inspect = ObjectID.prototype.toString;
188 |
189 | /**
190 | * Converts to its JSON representation.
191 | *
192 | * @return {String} return the 24 byte hex string representation.
193 | * @ignore
194 | */
195 | ObjectID.prototype.toJSON = function() {
196 | return this.toHexString();
197 | };
198 |
199 | /**
200 | * Compares the equality of this ObjectID with `otherID`.
201 | *
202 | * @method
203 | * @param {object} otherID ObjectID instance to compare against.
204 | * @return {boolean} the result of comparing two ObjectID's
205 | */
206 | ObjectID.prototype.equals = function equals (otherId) {
207 | var id;
208 |
209 | if(otherId instanceof ObjectID) {
210 | return this.toString() == otherId.toString();
211 | } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) {
212 | return otherId === this.id.toString('binary');
213 | } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) {
214 | return otherId.toLowerCase() === this.toHexString();
215 | } else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) {
216 | return otherId === this.id;
217 | } else if(otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
218 | return otherId.toHexString() === this.toHexString();
219 | } else {
220 | return false;
221 | }
222 | }
223 |
224 | /**
225 | * Returns the generation date (accurate up to the second) that this ID was generated.
226 | *
227 | * @method
228 | * @return {date} the generation date
229 | */
230 | ObjectID.prototype.getTimestamp = function() {
231 | var timestamp = new Date();
232 | var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
233 | timestamp.setTime(Math.floor(time) * 1000);
234 | return timestamp;
235 | }
236 |
237 | /**
238 | * @ignore
239 | */
240 | ObjectID.index = ~~(Math.random() * 0xFFFFFF);
241 |
242 | /**
243 | * @ignore
244 | */
245 | ObjectID.createPk = function createPk () {
246 | return new ObjectID();
247 | };
248 |
249 | /**
250 | * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
251 | *
252 | * @method
253 | * @param {number} time an integer number representing a number of seconds.
254 | * @return {ObjectID} return the created ObjectID
255 | */
256 | ObjectID.createFromTime = function createFromTime (time) {
257 | var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
258 | // Encode time into first 4 bytes
259 | buffer[3] = time & 0xff;
260 | buffer[2] = (time >> 8) & 0xff;
261 | buffer[1] = (time >> 16) & 0xff;
262 | buffer[0] = (time >> 24) & 0xff;
263 | // Return the new objectId
264 | return new ObjectID(buffer);
265 | };
266 |
267 | // Lookup tables
268 | var encodeLookup = '0123456789abcdef'.split('')
269 | var decodeLookup = []
270 | var i = 0
271 | while (i < 10) decodeLookup[0x30 + i] = i++
272 | while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++
273 |
274 | var _Buffer = Buffer;
275 | var convertToHex = function(bytes) {
276 | return bytes.toString('hex');
277 | }
278 |
279 | /**
280 | * Creates an ObjectID from a hex string representation of an ObjectID.
281 | *
282 | * @method
283 | * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
284 | * @return {ObjectID} return the created ObjectID
285 | */
286 | ObjectID.createFromHexString = function createFromHexString (string) {
287 | // Throw an error if it's not a valid setup
288 | if(typeof string === 'undefined' || string != null && string.length != 24) {
289 | throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
290 | }
291 |
292 | // Use Buffer.from method if available
293 | if(hasBufferType) return new ObjectID(new Buffer(string, 'hex'));
294 |
295 | // Calculate lengths
296 | var array = new _Buffer(12);
297 | var n = 0;
298 | var i = 0;
299 |
300 | while (i < 24) {
301 | array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]
302 | }
303 |
304 | return new ObjectID(array);
305 | };
306 |
307 | /**
308 | * Checks if a value is a valid bson ObjectId
309 | *
310 | * @method
311 | * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
312 | */
313 | ObjectID.isValid = function isValid(id) {
314 | if(id == null) return false;
315 |
316 | if(typeof id == 'number') {
317 | return true;
318 | }
319 |
320 | if(typeof id == 'string') {
321 | return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id));
322 | }
323 |
324 | if(id instanceof ObjectID) {
325 | return true;
326 | }
327 |
328 | if(id instanceof _Buffer) {
329 | return true;
330 | }
331 |
332 | // Duck-Typing detection of ObjectId like objects
333 | if(id.toHexString) {
334 | return id.id.length == 12 || (id.id.length == 24 && checkForHexRegExp.test(id.id));
335 | }
336 |
337 | return false;
338 | };
339 |
340 | /**
341 | * @ignore
342 | */
343 | Object.defineProperty(ObjectID.prototype, "generationTime", {
344 | enumerable: true
345 | , get: function () {
346 | return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
347 | }
348 | , set: function (value) {
349 | // Encode time into first 4 bytes
350 | this.id[3] = value & 0xff;
351 | this.id[2] = (value >> 8) & 0xff;
352 | this.id[1] = (value >> 16) & 0xff;
353 | this.id[0] = (value >> 24) & 0xff;
354 | }
355 | });
356 |
357 | /**
358 | * Expose.
359 | */
360 | module.exports = ObjectID;
361 | module.exports.ObjectID = ObjectID;
362 | module.exports.ObjectId = ObjectID;
--------------------------------------------------------------------------------
/dist/objectid.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Machine id.
5 | *
6 | * Create a random 3-byte value (i.e. unique for this
7 | * process). Other drivers use a md5 of the machine id here, but
8 | * that would mean an asyc call to gethostname, so we don't bother.
9 | * @ignore
10 | */
11 | var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10);
12 |
13 | // Regular expression that checks for hex value
14 | var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
15 | var hasBufferType = false;
16 |
17 | // Check if buffer exists
18 | try {
19 | if (Buffer && Buffer.from) hasBufferType = true;
20 | } catch (err) {};
21 |
22 | /**
23 | * Create a new ObjectID instance
24 | *
25 | * @class
26 | * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
27 | * @property {number} generationTime The generation time of this ObjectId instance
28 | * @return {ObjectID} instance of ObjectID.
29 | */
30 | var ObjectID = function ObjectID(id) {
31 | // Duck-typing to support ObjectId from different npm packages
32 | if (id instanceof ObjectID) return id;
33 | if (!(this instanceof ObjectID)) return new ObjectID(id);
34 |
35 | this._bsontype = 'ObjectID';
36 |
37 | // The most common usecase (blank id, new objectId instance)
38 | if (id == null || typeof id == 'number') {
39 | // Generate a new id
40 | this.id = this.generate(id);
41 | // If we are caching the hex string
42 | if (ObjectID.cacheHexString) this.__id = this.toString('hex');
43 | // Return the object
44 | return;
45 | }
46 |
47 | // Check if the passed in id is valid
48 | var valid = ObjectID.isValid(id);
49 |
50 | // Throw an error if it's not a valid setup
51 | if (!valid && id != null) {
52 | throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
53 | } else if (valid && typeof id == 'string' && id.length == 24 && hasBufferType) {
54 | return new ObjectID(new Buffer(id, 'hex'));
55 | } else if (valid && typeof id == 'string' && id.length == 24) {
56 | return ObjectID.createFromHexString(id);
57 | } else if (id != null && id.length === 12) {
58 | // assume 12 byte string
59 | this.id = id;
60 | } else if (id != null && id.toHexString) {
61 | // Duck-typing to support ObjectId from different npm packages
62 | return id;
63 | } else {
64 | throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
65 | }
66 |
67 | if (ObjectID.cacheHexString) this.__id = this.toString('hex');
68 | };
69 |
70 | // Allow usage of ObjectId as well as ObjectID
71 | var ObjectId = ObjectID;
72 |
73 | // Precomputed hex table enables speedy hex string conversion
74 | var hexTable = [];
75 | for (var i = 0; i < 256; i++) {
76 | hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16);
77 | }
78 |
79 | /**
80 | * Return the ObjectID id as a 24 byte hex string representation
81 | *
82 | * @method
83 | * @return {string} return the 24 byte hex string representation.
84 | */
85 | ObjectID.prototype.toHexString = function () {
86 | if (ObjectID.cacheHexString && this.__id) return this.__id;
87 |
88 | var hexString = '';
89 | if (!this.id || !this.id.length) {
90 | throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']');
91 | }
92 |
93 | if (this.id instanceof _Buffer) {
94 | hexString = convertToHex(this.id);
95 | if (ObjectID.cacheHexString) this.__id = hexString;
96 | return hexString;
97 | }
98 |
99 | for (var i = 0; i < this.id.length; i++) {
100 | hexString += hexTable[this.id.charCodeAt(i)];
101 | }
102 |
103 | if (ObjectID.cacheHexString) this.__id = hexString;
104 | return hexString;
105 | };
106 |
107 | /**
108 | * Update the ObjectID index used in generating new ObjectID's on the driver
109 | *
110 | * @method
111 | * @return {number} returns next index value.
112 | * @ignore
113 | */
114 | ObjectID.prototype.get_inc = function () {
115 | return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF;
116 | };
117 |
118 | /**
119 | * Update the ObjectID index used in generating new ObjectID's on the driver
120 | *
121 | * @method
122 | * @return {number} returns next index value.
123 | * @ignore
124 | */
125 | ObjectID.prototype.getInc = function () {
126 | return this.get_inc();
127 | };
128 |
129 | /**
130 | * Generate a 12 byte id buffer used in ObjectID's
131 | *
132 | * @method
133 | * @param {number} [time] optional parameter allowing to pass in a second based timestamp.
134 | * @return {Buffer} return the 12 byte id buffer string.
135 | */
136 | ObjectID.prototype.generate = function (time) {
137 | if ('number' != typeof time) {
138 | time = ~ ~(Date.now() / 1000);
139 | }
140 |
141 | // Use pid
142 | var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;
143 | var inc = this.get_inc();
144 | // Buffer used
145 | var buffer = new Buffer(12);
146 | // Encode time
147 | buffer[3] = time & 0xff;
148 | buffer[2] = time >> 8 & 0xff;
149 | buffer[1] = time >> 16 & 0xff;
150 | buffer[0] = time >> 24 & 0xff;
151 | // Encode machine
152 | buffer[6] = MACHINE_ID & 0xff;
153 | buffer[5] = MACHINE_ID >> 8 & 0xff;
154 | buffer[4] = MACHINE_ID >> 16 & 0xff;
155 | // Encode pid
156 | buffer[8] = pid & 0xff;
157 | buffer[7] = pid >> 8 & 0xff;
158 | // Encode index
159 | buffer[11] = inc & 0xff;
160 | buffer[10] = inc >> 8 & 0xff;
161 | buffer[9] = inc >> 16 & 0xff;
162 | // Return the buffer
163 | return buffer;
164 | };
165 |
166 | /**
167 | * Converts the id into a 24 byte hex string for printing
168 | *
169 | * @param {String} format The Buffer toString format parameter.
170 | * @return {String} return the 24 byte hex string representation.
171 | * @ignore
172 | */
173 | ObjectID.prototype.toString = function (format) {
174 | // Is the id a buffer then use the buffer toString method to return the format
175 | if (this.id && this.id.copy) {
176 | return this.id.toString(typeof format === 'string' ? format : 'hex');
177 | }
178 |
179 | // if(this.buffer )
180 | return this.toHexString();
181 | };
182 |
183 | /**
184 | * Converts to a string representation of this Id.
185 | *
186 | * @return {String} return the 24 byte hex string representation.
187 | * @ignore
188 | */
189 | ObjectID.prototype.inspect = ObjectID.prototype.toString;
190 |
191 | /**
192 | * Converts to its JSON representation.
193 | *
194 | * @return {String} return the 24 byte hex string representation.
195 | * @ignore
196 | */
197 | ObjectID.prototype.toJSON = function () {
198 | return this.toHexString();
199 | };
200 |
201 | /**
202 | * Compares the equality of this ObjectID with `otherID`.
203 | *
204 | * @method
205 | * @param {object} otherID ObjectID instance to compare against.
206 | * @return {boolean} the result of comparing two ObjectID's
207 | */
208 | ObjectID.prototype.equals = function equals(otherId) {
209 | var id;
210 |
211 | if (otherId instanceof ObjectID) {
212 | return this.toString() == otherId.toString();
213 | } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) {
214 | return otherId === this.id.toString('binary');
215 | } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) {
216 | return otherId.toLowerCase() === this.toHexString();
217 | } else if (typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) {
218 | return otherId === this.id;
219 | } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
220 | return otherId.toHexString() === this.toHexString();
221 | } else {
222 | return false;
223 | }
224 | };
225 |
226 | /**
227 | * Returns the generation date (accurate up to the second) that this ID was generated.
228 | *
229 | * @method
230 | * @return {date} the generation date
231 | */
232 | ObjectID.prototype.getTimestamp = function () {
233 | var timestamp = new Date();
234 | var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
235 | timestamp.setTime(Math.floor(time) * 1000);
236 | return timestamp;
237 | };
238 |
239 | /**
240 | * @ignore
241 | */
242 | ObjectID.index = ~ ~(Math.random() * 0xFFFFFF);
243 |
244 | /**
245 | * @ignore
246 | */
247 | ObjectID.createPk = function createPk() {
248 | return new ObjectID();
249 | };
250 |
251 | /**
252 | * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID.
253 | *
254 | * @method
255 | * @param {number} time an integer number representing a number of seconds.
256 | * @return {ObjectID} return the created ObjectID
257 | */
258 | ObjectID.createFromTime = function createFromTime(time) {
259 | var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
260 | // Encode time into first 4 bytes
261 | buffer[3] = time & 0xff;
262 | buffer[2] = time >> 8 & 0xff;
263 | buffer[1] = time >> 16 & 0xff;
264 | buffer[0] = time >> 24 & 0xff;
265 | // Return the new objectId
266 | return new ObjectID(buffer);
267 | };
268 |
269 | // Lookup tables
270 | var encodeLookup = '0123456789abcdef'.split('');
271 | var decodeLookup = [];
272 | var i = 0;
273 | while (i < 10) {
274 | decodeLookup[0x30 + i] = i++;
275 | }while (i < 16) {
276 | decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++;
277 | }var _Buffer = Buffer;
278 | var convertToHex = function convertToHex(bytes) {
279 | return bytes.toString('hex');
280 | };
281 |
282 | /**
283 | * Creates an ObjectID from a hex string representation of an ObjectID.
284 | *
285 | * @method
286 | * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring.
287 | * @return {ObjectID} return the created ObjectID
288 | */
289 | ObjectID.createFromHexString = function createFromHexString(string) {
290 | // Throw an error if it's not a valid setup
291 | if (typeof string === 'undefined' || string != null && string.length != 24) {
292 | throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
293 | }
294 |
295 | // Use Buffer.from method if available
296 | if (hasBufferType) return new ObjectID(new Buffer(string, 'hex'));
297 |
298 | // Calculate lengths
299 | var array = new _Buffer(12);
300 | var n = 0;
301 | var i = 0;
302 |
303 | while (i < 24) {
304 | array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)];
305 | }
306 |
307 | return new ObjectID(array);
308 | };
309 |
310 | /**
311 | * Checks if a value is a valid bson ObjectId
312 | *
313 | * @method
314 | * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise.
315 | */
316 | ObjectID.isValid = function isValid(id) {
317 | if (id == null) return false;
318 |
319 | if (typeof id == 'number') {
320 | return true;
321 | }
322 |
323 | if (typeof id == 'string') {
324 | return id.length == 12 || id.length == 24 && checkForHexRegExp.test(id);
325 | }
326 |
327 | if (id instanceof ObjectID) {
328 | return true;
329 | }
330 |
331 | if (id instanceof _Buffer) {
332 | return true;
333 | }
334 |
335 | // Duck-Typing detection of ObjectId like objects
336 | if (id.toHexString) {
337 | return id.id.length == 12 || id.id.length == 24 && checkForHexRegExp.test(id.id);
338 | }
339 |
340 | return false;
341 | };
342 |
343 | /**
344 | * @ignore
345 | */
346 | Object.defineProperty(ObjectID.prototype, "generationTime", {
347 | enumerable: true,
348 | get: function get() {
349 | return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24;
350 | },
351 | set: function set(value) {
352 | // Encode time into first 4 bytes
353 | this.id[3] = value & 0xff;
354 | this.id[2] = value >> 8 & 0xff;
355 | this.id[1] = value >> 16 & 0xff;
356 | this.id[0] = value >> 24 & 0xff;
357 | }
358 | });
359 |
360 | /**
361 | * Expose.
362 | */
363 | module.exports = ObjectID;
364 | module.exports.ObjectID = ObjectID;
365 | module.exports.ObjectId = ObjectID;
--------------------------------------------------------------------------------