@niledatabase/server 2.1.2-alpha.1 → 2.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,13 +7,15 @@ Consolidates the API and DB for working with Nile.
7
7
  ### With configuration object
8
8
 
9
9
  ```ts
10
- import Server from '@niledatabase/server';
10
+ import Nile from '@niledatabase/server';
11
11
 
12
- const nile = Server({
12
+ const nile = new Nile({
13
13
  user: 'username',
14
14
  password: 'password',
15
15
  });
16
16
 
17
+ await nile.init();
18
+
17
19
  await nile.api.createTenant({ name: 'name' });
18
20
 
19
21
  await nile.db.query('select * from todo');
@@ -27,18 +29,20 @@ NILEDB_PASSWORD=password
27
29
  ```
28
30
 
29
31
  ```ts
30
- import Server from '@niledatabase/server';
32
+ import Nile from '@niledatabase/server';
33
+
34
+ const nile = new Nile();
31
35
 
32
- const nile = Server();
36
+ await nile.init();
33
37
 
34
38
  await nile.api.createTenant({ name: 'name' });
35
39
 
36
40
  await nile.db.query('select * from todo');
37
41
  ```
38
42
 
39
- ## Auto-configuration
43
+ ## Initialization
40
44
 
41
- In addition to `user` and `password`, a fully configured SDK must also have values for `db.host`, `databaseName`, and `databaseId`. If the values are not provided in either the `.env` file or the instance configuration, the SDK will automatically phone home to configure itself. For production, it is recommended to set those values.
45
+ In addition to `user` and `password`, a fully configured SDK must also have values for `db.host`, `databaseName`, and `databaseId`. If the values are not provided in either the `.env` file or the instance configuration, the `init()` function should be called, which will allow the SDK to automatically configure itself. For production, it is recommended to set those values.
42
46
 
43
47
  ## Configuration
44
48
 
package/dist/Server.d.ts CHANGED
@@ -16,6 +16,7 @@ declare class Server {
16
16
  private servers;
17
17
  constructor(config?: ServerConfig);
18
18
  setConfig(cfg: Config): void;
19
+ init(cfg?: Config): Promise<void>;
19
20
  set databaseId(val: string | void);
20
21
  get userId(): string | undefined | null;
21
22
  set userId(userId: string | undefined | null);
@@ -31,5 +32,4 @@ declare class Server {
31
32
  */
32
33
  getInstance(config: ServerConfig): Server;
33
34
  }
34
- export default function Nile(config?: ServerConfig): Server;
35
- export {};
35
+ export default Server;
@@ -1,9 +1,9 @@
1
1
  import { Pool } from 'pg';
2
- import { Config } from '../utils/Config';
2
+ import { ServerConfig } from '../types';
3
3
  import NileDatabase from './NileInstance';
4
4
  export default class DBManager {
5
5
  connections: Map<string, NileDatabase>;
6
6
  private makeId;
7
- constructor(config: Config);
8
- getConnection(config: Config): Pool;
7
+ constructor(config: ServerConfig);
8
+ getConnection(config: ServerConfig): Pool;
9
9
  }
@@ -2,7 +2,6 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var syncFetch = require('sync-fetch');
6
5
  require('dotenv/config');
7
6
  var isEmpty = require('lodash/isEmpty');
8
7
  var isObject = require('lodash/isObject');
@@ -647,8 +646,10 @@ var ApiConfig = /*#__PURE__*/function () {
647
646
  }]);
648
647
  }();
649
648
  var Config = /*#__PURE__*/function () {
650
- function Config(config, allowPhoneHome) {
651
- var _config$api$cookieKey, _config$api;
649
+ function Config(_config) {
650
+ var _this = this,
651
+ _config$api$cookieKey2,
652
+ _config$api2;
652
653
  this.user = void 0;
653
654
  this.password = void 0;
654
655
  this.databaseId = void 0;
@@ -658,69 +659,151 @@ var Config = /*#__PURE__*/function () {
658
659
  this.api = void 0;
659
660
  this._tenantId = void 0;
660
661
  this._userId = void 0;
661
- var _Logger = Logger(config, '[config]'),
662
- info = _Logger.info,
663
- error = _Logger.error;
664
- var envVarConfig = {
665
- config: config
666
- };
667
- if (allowPhoneHome) {
668
- envVarConfig.logger = '[config]';
669
- }
670
- this.databaseId = getDatbaseId(envVarConfig);
671
- this.user = getUsername(envVarConfig);
672
- this.password = getPassword(envVarConfig);
673
- this.databaseName = getDatabaseName(envVarConfig);
674
- this._tenantId = getTenantId(envVarConfig);
675
- this.debug = Boolean(config == null ? void 0 : config.debug);
676
- var basePath = getBasePath(envVarConfig);
677
- var host = getDbHost(envVarConfig);
678
- var port = getDbPort(envVarConfig);
679
- this._userId = config == null ? void 0 : config.userId;
680
- if (allowPhoneHome && (!host || !this.databaseName || !this.databaseId)) {
681
- var database = getInfo(config);
682
- info('[fetched database]', database);
683
- {
684
- if ('message' in database) {
685
- if ('statusCode' in database) {
686
- error(database);
687
- throw new Error('HTTP error has occured');
688
- } else {
689
- throw new Error('Unable to auto-configure. Please set or remove NILEDB_API, NILEDB_NAME, and NILEDB_HOST in your .env file.');
662
+ this.configure = /*#__PURE__*/function () {
663
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config) {
664
+ var _config$api$cookieKey, _config$api;
665
+ var _Logger, info, error, envVarConfig, basePath, host, port, databaseName, url, res, database, possibleError, json, message, _database, apiHost, dbHost, name, id, dburl, apiurl;
666
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
667
+ while (1) switch (_context.prev = _context.next) {
668
+ case 0:
669
+ _Logger = Logger(config, '[init]'), info = _Logger.info, error = _Logger.error;
670
+ envVarConfig = {
671
+ config: config
672
+ };
673
+ basePath = getBasePath(envVarConfig);
674
+ host = getDbHost(envVarConfig);
675
+ port = getDbPort(envVarConfig);
676
+ databaseName = getDatabaseName({
677
+ config: config,
678
+ logger: 'getInfo'
679
+ });
680
+ url = new URL(basePath + "/databases/configure");
681
+ if (databaseName) {
682
+ url.searchParams.set('databaseName', databaseName);
683
+ }
684
+ info(url.href);
685
+ _context.next = 11;
686
+ return fetch(url, {
687
+ headers: {
688
+ Authorization: "Bearer " + getInfoBearer({
689
+ config: config
690
+ })
691
+ }
692
+ });
693
+ case 11:
694
+ res = _context.sent;
695
+ possibleError = res.clone();
696
+ _context.prev = 13;
697
+ _context.next = 16;
698
+ return res.json();
699
+ case 16:
700
+ json = _context.sent;
701
+ if (res.status === 404) {
702
+ info('is the configured databaseName correct?');
703
+ }
704
+ if (json.status && json.status !== 'READY') {
705
+ database = {
706
+ message: 'Database is not ready yet'
707
+ };
708
+ } else {
709
+ database = json;
710
+ }
711
+ _context.next = 28;
712
+ break;
713
+ case 21:
714
+ _context.prev = 21;
715
+ _context.t0 = _context["catch"](13);
716
+ _context.next = 25;
717
+ return possibleError.text();
718
+ case 25:
719
+ message = _context.sent;
720
+ error(message);
721
+ database = {
722
+ message: message
723
+ };
724
+ case 28:
725
+ if (!(!host || !_this.databaseName || !_this.databaseId)) {
726
+ _context.next = 39;
727
+ break;
728
+ }
729
+ info('[fetched database]', database);
730
+ if (!('message' in database)) {
731
+ _context.next = 38;
732
+ break;
733
+ }
734
+ if (!('statusCode' in database)) {
735
+ _context.next = 37;
736
+ break;
737
+ }
738
+ error(database);
739
+ throw new Error('HTTP error has occured');
740
+ case 37:
741
+ throw new Error('Unable to auto-configure. Please set or remove NILEDB_API, NILEDB_NAME, and NILEDB_HOST in your .env file.');
742
+ case 38:
743
+ if (typeof database === 'object') {
744
+ _database = database, apiHost = _database.apiHost, dbHost = _database.dbHost, name = _database.name, id = _database.id;
745
+ _this.databaseId = id;
746
+ _this.databaseName = name;
747
+ // gotta do something dumb here
748
+ dburl = new URL(dbHost);
749
+ apiurl = new URL(apiHost);
750
+ host = dburl.host;
751
+ basePath = apiurl.origin;
752
+ }
753
+ case 39:
754
+ _this.api = new ApiConfig({
755
+ basePath: basePath,
756
+ cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
757
+ token: getToken({
758
+ config: config
759
+ })
760
+ });
761
+ _this.db = _extends({
762
+ user: _this.user,
763
+ password: _this.password,
764
+ host: host,
765
+ port: port,
766
+ database: _this.databaseName
767
+ }, typeof (config == null ? void 0 : config.db) === 'object' ? config.db : {});
768
+ info('[config set]', _this);
769
+ return _context.abrupt("return", _this);
770
+ case 43:
771
+ case "end":
772
+ return _context.stop();
690
773
  }
691
- }
692
- if (typeof database === 'object') {
693
- var apiHost = database.apiHost,
694
- dbHost = database.dbHost,
695
- name = database.name,
696
- id = database.id;
697
- this.databaseId = id;
698
- this.databaseName = name;
699
- // gotta do something dumb here
700
- var dburl = new URL(dbHost);
701
- var apiurl = new URL(apiHost);
702
- host = dburl.host;
703
- basePath = apiurl.origin;
704
- }
705
- }
706
- }
774
+ }, _callee, null, [[13, 21]]);
775
+ }));
776
+ return function (_x) {
777
+ return _ref2.apply(this, arguments);
778
+ };
779
+ }();
780
+ var _envVarConfig = {
781
+ config: _config
782
+ };
783
+ this.databaseId = getDatbaseId(_envVarConfig);
784
+ this.user = getUsername(_envVarConfig);
785
+ this.password = getPassword(_envVarConfig);
786
+ this.databaseName = getDatabaseName(_envVarConfig);
787
+ this._tenantId = getTenantId(_envVarConfig);
788
+ this.debug = Boolean(_config == null ? void 0 : _config.debug);
789
+ this._userId = _config == null ? void 0 : _config.userId;
790
+ var _basePath = getBasePath(_envVarConfig);
791
+ var _host = getDbHost(_envVarConfig);
792
+ var _port = getDbPort(_envVarConfig);
707
793
  this.api = new ApiConfig({
708
- basePath: basePath,
709
- cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
794
+ basePath: _basePath,
795
+ cookieKey: (_config$api$cookieKey2 = _config == null || (_config$api2 = _config.api) == null ? void 0 : _config$api2.cookieKey) != null ? _config$api$cookieKey2 : 'token',
710
796
  token: getToken({
711
- config: config
797
+ config: _config
712
798
  })
713
799
  });
714
800
  this.db = _extends({
715
801
  user: this.user,
716
802
  password: this.password,
717
- host: host,
718
- port: port,
803
+ host: _host,
804
+ port: _port,
719
805
  database: this.databaseName
720
- }, typeof (config == null ? void 0 : config.db) === 'object' ? config.db : {});
721
- if (allowPhoneHome) {
722
- info(this);
723
- }
806
+ }, typeof (_config == null ? void 0 : _config.db) === 'object' ? _config.db : {});
724
807
  }
725
808
  return _createClass(Config, [{
726
809
  key: "tenantId",
@@ -740,49 +823,6 @@ var Config = /*#__PURE__*/function () {
740
823
  }
741
824
  }]);
742
825
  }();
743
- function getInfo(config) {
744
- var basePath = getBasePath({
745
- config: config
746
- });
747
- var databaseName = getDatabaseName({
748
- config: config,
749
- logger: 'getInfo'
750
- });
751
- var url = new URL(basePath + "/databases/configure");
752
- if (databaseName) {
753
- url.searchParams.set('databaseName', databaseName);
754
- }
755
- var _Logger2 = Logger(config, '[getInfo]'),
756
- info = _Logger2.info,
757
- error = _Logger2.error;
758
- info(url.href);
759
- var res = syncFetch(url, {
760
- headers: {
761
- Authorization: "Bearer " + getInfoBearer({
762
- config: config
763
- })
764
- }
765
- });
766
- var possibleError = res.clone();
767
- try {
768
- var json = res.json();
769
- if (res.status === 404) {
770
- info('is the configured databaseName correct?');
771
- }
772
- if (json.status && json.status !== 'READY') {
773
- return {
774
- message: 'Database is not ready yet'
775
- };
776
- }
777
- return json;
778
- } catch (e) {
779
- var message = possibleError.text();
780
- error(message);
781
- return {
782
- message: message
783
- };
784
- }
785
- }
786
826
 
787
827
  var ResponseError = function ResponseError(body, init) {
788
828
  this.response = void 0;
@@ -1925,15 +1965,15 @@ var makeServerId = function makeServerId(config) {
1925
1965
  return Buffer.from(JSON.stringify(config), 'base64').toString();
1926
1966
  };
1927
1967
 
1928
- var init = function init(config) {
1968
+ var _init = function init(config) {
1929
1969
  var auth = new Auth(config);
1930
1970
  var users = new Users(config);
1931
1971
  var tenants = new Tenants(config);
1932
- return [{
1972
+ return {
1933
1973
  auth: auth,
1934
1974
  users: users,
1935
1975
  tenants: tenants
1936
- }];
1976
+ };
1937
1977
  };
1938
1978
  var Server = /*#__PURE__*/function () {
1939
1979
  function Server(config) {
@@ -1942,11 +1982,9 @@ var Server = /*#__PURE__*/function () {
1942
1982
  this.api = void 0;
1943
1983
  this.manager = void 0;
1944
1984
  this.servers = void 0;
1945
- this.config = new Config(config, true);
1985
+ this.config = new Config(config);
1946
1986
  this.servers = new Map();
1947
- var _init = init(this.config),
1948
- api = _init[0];
1949
- this.api = api;
1987
+ this.api = _init(this.config);
1950
1988
  this.manager = new DBManager(this.config);
1951
1989
  watchTenantId(function (tenantId) {
1952
1990
  _this.tenantId = tenantId;
@@ -1960,8 +1998,32 @@ var Server = /*#__PURE__*/function () {
1960
1998
  }
1961
1999
  var _proto = Server.prototype;
1962
2000
  _proto.setConfig = function setConfig(cfg) {
1963
- this.config = new Config(cfg, false);
2001
+ this.config = new Config(cfg);
1964
2002
  };
2003
+ _proto.init = /*#__PURE__*/function () {
2004
+ var _init2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cfg) {
2005
+ var updatedConfig;
2006
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
2007
+ while (1) switch (_context.prev = _context.next) {
2008
+ case 0:
2009
+ _context.next = 2;
2010
+ return this.config.configure(_extends({}, this.config, cfg));
2011
+ case 2:
2012
+ updatedConfig = _context.sent;
2013
+ this.setConfig(updatedConfig);
2014
+ this.manager = new DBManager(this.config);
2015
+ this.api = _init(updatedConfig);
2016
+ case 6:
2017
+ case "end":
2018
+ return _context.stop();
2019
+ }
2020
+ }, _callee, this);
2021
+ }));
2022
+ function init(_x) {
2023
+ return _init2.apply(this, arguments);
2024
+ }
2025
+ return init;
2026
+ }();
1965
2027
  /**
1966
2028
  * A utility function if you want to manage different NileDB instances yourself
1967
2029
  * returns the global Server object, an existing server that's already been configured,
@@ -1977,7 +2039,7 @@ var Server = /*#__PURE__*/function () {
1977
2039
  var existing = this.servers.get(serverId);
1978
2040
  if (existing) {
1979
2041
  // be sure the config is up to date
1980
- var updatedConfig = new Config(_config, false);
2042
+ var updatedConfig = new Config(_config);
1981
2043
  existing.setConfig(updatedConfig);
1982
2044
  // propagage special config items
1983
2045
  existing.tenantId = updatedConfig.tenantId;
@@ -2050,14 +2112,7 @@ var Server = /*#__PURE__*/function () {
2050
2112
  return this.manager.getConnection(this.config);
2051
2113
  }
2052
2114
  }]);
2053
- }(); // export default Server;
2054
- function Nile(config) {
2055
- var server = new Server(config);
2056
- // server.setConfig(new Config(config as ServerConfig, false));
2057
- return server;
2058
- }
2059
-
2060
- module.exports = Nile;
2115
+ }();
2061
2116
 
2062
- exports.default = Nile;
2117
+ exports.default = Server;
2063
2118
  //# sourceMappingURL=server.cjs.development.js.map