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

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
  }
@@ -647,8 +647,10 @@ var ApiConfig = /*#__PURE__*/function () {
647
647
  }]);
648
648
  }();
649
649
  var Config = /*#__PURE__*/function () {
650
- function Config(config, allowPhoneHome) {
651
- var _config$api$cookieKey, _config$api;
650
+ function Config(_config) {
651
+ var _this = this,
652
+ _config$api$cookieKey2,
653
+ _config$api2;
652
654
  this.user = void 0;
653
655
  this.password = void 0;
654
656
  this.databaseId = void 0;
@@ -658,69 +660,138 @@ var Config = /*#__PURE__*/function () {
658
660
  this.api = void 0;
659
661
  this._tenantId = void 0;
660
662
  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.');
663
+ this.configure = /*#__PURE__*/function () {
664
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(config) {
665
+ var _config$api$cookieKey, _config$api;
666
+ var _Logger, info, error, envVarConfig, basePath, host, port, databaseName, url, res, database, possibleError, json, message, _database, apiHost, dbHost, name, id, dburl, apiurl;
667
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
668
+ while (1) switch (_context.prev = _context.next) {
669
+ case 0:
670
+ _Logger = Logger(config, '[init]'), info = _Logger.info, error = _Logger.error;
671
+ envVarConfig = {
672
+ config: config
673
+ };
674
+ basePath = getBasePath(envVarConfig);
675
+ host = getDbHost(envVarConfig);
676
+ port = getDbPort(envVarConfig);
677
+ databaseName = getDatabaseName({
678
+ config: config,
679
+ logger: 'getInfo'
680
+ });
681
+ url = new URL(basePath + "/databases/configure");
682
+ if (databaseName) {
683
+ url.searchParams.set('databaseName', databaseName);
684
+ }
685
+ info(url.href);
686
+ res = syncFetch(url, {
687
+ headers: {
688
+ Authorization: "Bearer " + getInfoBearer({
689
+ config: config
690
+ })
691
+ }
692
+ });
693
+ possibleError = res.clone();
694
+ try {
695
+ json = res.json();
696
+ if (res.status === 404) {
697
+ info('is the configured databaseName correct?');
698
+ }
699
+ if (json.status && json.status !== 'READY') {
700
+ database = {
701
+ message: 'Database is not ready yet'
702
+ };
703
+ } else {
704
+ database = json;
705
+ }
706
+ } catch (e) {
707
+ message = possibleError.text();
708
+ error(message);
709
+ database = {
710
+ message: message
711
+ };
712
+ }
713
+ if (!(!host || !_this.databaseName || !_this.databaseId)) {
714
+ _context.next = 23;
715
+ break;
716
+ }
717
+ info('[fetched database]', database);
718
+ if (!('message' in database)) {
719
+ _context.next = 22;
720
+ break;
721
+ }
722
+ if (!('statusCode' in database)) {
723
+ _context.next = 21;
724
+ break;
725
+ }
726
+ error(database);
727
+ throw new Error('HTTP error has occured');
728
+ case 21:
729
+ throw new Error('Unable to auto-configure. Please set or remove NILEDB_API, NILEDB_NAME, and NILEDB_HOST in your .env file.');
730
+ case 22:
731
+ if (typeof database === 'object') {
732
+ _database = database, apiHost = _database.apiHost, dbHost = _database.dbHost, name = _database.name, id = _database.id;
733
+ _this.databaseId = id;
734
+ _this.databaseName = name;
735
+ // gotta do something dumb here
736
+ dburl = new URL(dbHost);
737
+ apiurl = new URL(apiHost);
738
+ host = dburl.host;
739
+ basePath = apiurl.origin;
740
+ }
741
+ case 23:
742
+ _this.api = new ApiConfig({
743
+ basePath: basePath,
744
+ cookieKey: (_config$api$cookieKey = config == null || (_config$api = config.api) == null ? void 0 : _config$api.cookieKey) != null ? _config$api$cookieKey : 'token',
745
+ token: getToken({
746
+ config: config
747
+ })
748
+ });
749
+ _this.db = _extends({
750
+ user: _this.user,
751
+ password: _this.password,
752
+ host: host,
753
+ port: port,
754
+ database: _this.databaseName
755
+ }, typeof (config == null ? void 0 : config.db) === 'object' ? config.db : {});
756
+ info('[config set]', _this);
757
+ return _context.abrupt("return", _this);
758
+ case 27:
759
+ case "end":
760
+ return _context.stop();
690
761
  }
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
- }
762
+ }, _callee);
763
+ }));
764
+ return function (_x) {
765
+ return _ref2.apply(this, arguments);
766
+ };
767
+ }();
768
+ var _envVarConfig = {
769
+ config: _config
770
+ };
771
+ this.databaseId = getDatbaseId(_envVarConfig);
772
+ this.user = getUsername(_envVarConfig);
773
+ this.password = getPassword(_envVarConfig);
774
+ this.databaseName = getDatabaseName(_envVarConfig);
775
+ this._tenantId = getTenantId(_envVarConfig);
776
+ this.debug = Boolean(_config == null ? void 0 : _config.debug);
777
+ this._userId = _config == null ? void 0 : _config.userId;
778
+ var _basePath = getBasePath(_envVarConfig);
779
+ var _host = getDbHost(_envVarConfig);
780
+ var _port = getDbPort(_envVarConfig);
707
781
  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',
782
+ basePath: _basePath,
783
+ cookieKey: (_config$api$cookieKey2 = _config == null || (_config$api2 = _config.api) == null ? void 0 : _config$api2.cookieKey) != null ? _config$api$cookieKey2 : 'token',
710
784
  token: getToken({
711
- config: config
785
+ config: _config
712
786
  })
713
787
  });
714
788
  this.db = _extends({
715
789
  user: this.user,
716
790
  password: this.password,
717
- host: host,
718
- port: port,
791
+ host: _host,
792
+ port: _port,
719
793
  database: this.databaseName
720
- }, typeof (config == null ? void 0 : config.db) === 'object' ? config.db : {});
721
- if (allowPhoneHome) {
722
- info(this);
723
- }
794
+ }, typeof (_config == null ? void 0 : _config.db) === 'object' ? _config.db : {});
724
795
  }
725
796
  return _createClass(Config, [{
726
797
  key: "tenantId",
@@ -740,49 +811,6 @@ var Config = /*#__PURE__*/function () {
740
811
  }
741
812
  }]);
742
813
  }();
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
814
 
787
815
  var ResponseError = function ResponseError(body, init) {
788
816
  this.response = void 0;
@@ -1925,15 +1953,15 @@ var makeServerId = function makeServerId(config) {
1925
1953
  return Buffer.from(JSON.stringify(config), 'base64').toString();
1926
1954
  };
1927
1955
 
1928
- var init = function init(config) {
1956
+ var _init = function init(config) {
1929
1957
  var auth = new Auth(config);
1930
1958
  var users = new Users(config);
1931
1959
  var tenants = new Tenants(config);
1932
- return [{
1960
+ return {
1933
1961
  auth: auth,
1934
1962
  users: users,
1935
1963
  tenants: tenants
1936
- }];
1964
+ };
1937
1965
  };
1938
1966
  var Server = /*#__PURE__*/function () {
1939
1967
  function Server(config) {
@@ -1942,11 +1970,9 @@ var Server = /*#__PURE__*/function () {
1942
1970
  this.api = void 0;
1943
1971
  this.manager = void 0;
1944
1972
  this.servers = void 0;
1945
- this.config = new Config(config, true);
1973
+ this.config = new Config(config);
1946
1974
  this.servers = new Map();
1947
- var _init = init(this.config),
1948
- api = _init[0];
1949
- this.api = api;
1975
+ this.api = _init(this.config);
1950
1976
  this.manager = new DBManager(this.config);
1951
1977
  watchTenantId(function (tenantId) {
1952
1978
  _this.tenantId = tenantId;
@@ -1960,8 +1986,32 @@ var Server = /*#__PURE__*/function () {
1960
1986
  }
1961
1987
  var _proto = Server.prototype;
1962
1988
  _proto.setConfig = function setConfig(cfg) {
1963
- this.config = new Config(cfg, false);
1989
+ this.config = new Config(cfg);
1964
1990
  };
1991
+ _proto.init = /*#__PURE__*/function () {
1992
+ var _init2 = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(cfg) {
1993
+ var updatedConfig;
1994
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1995
+ while (1) switch (_context.prev = _context.next) {
1996
+ case 0:
1997
+ _context.next = 2;
1998
+ return this.config.configure(_extends({}, this.config, cfg));
1999
+ case 2:
2000
+ updatedConfig = _context.sent;
2001
+ this.setConfig(updatedConfig);
2002
+ this.manager = new DBManager(this.config);
2003
+ this.api = _init(updatedConfig);
2004
+ case 6:
2005
+ case "end":
2006
+ return _context.stop();
2007
+ }
2008
+ }, _callee, this);
2009
+ }));
2010
+ function init(_x) {
2011
+ return _init2.apply(this, arguments);
2012
+ }
2013
+ return init;
2014
+ }();
1965
2015
  /**
1966
2016
  * A utility function if you want to manage different NileDB instances yourself
1967
2017
  * returns the global Server object, an existing server that's already been configured,
@@ -1977,7 +2027,7 @@ var Server = /*#__PURE__*/function () {
1977
2027
  var existing = this.servers.get(serverId);
1978
2028
  if (existing) {
1979
2029
  // be sure the config is up to date
1980
- var updatedConfig = new Config(_config, false);
2030
+ var updatedConfig = new Config(_config);
1981
2031
  existing.setConfig(updatedConfig);
1982
2032
  // propagage special config items
1983
2033
  existing.tenantId = updatedConfig.tenantId;
@@ -2050,14 +2100,7 @@ var Server = /*#__PURE__*/function () {
2050
2100
  return this.manager.getConnection(this.config);
2051
2101
  }
2052
2102
  }]);
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;
2103
+ }();
2061
2104
 
2062
- exports.default = Nile;
2105
+ exports.default = Server;
2063
2106
  //# sourceMappingURL=server.cjs.development.js.map