diff --git a/README.md b/README.md
index 6c15472..d93b80a 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,10 @@
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=for-the-badge)](https://github.com/semantic-release/semantic-release)
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=for-the-badge)](https://github.com/prettier/prettier)
-
+## Checkout our awesome [examples/showcases][examples] repo.
+
+
+
**Rich Data Services** (or **RDS**) is a suite of REST APIs designed by Metadata Technology North America (MTNA) to meet various needs for data engineers, managers, custodians, and consumers. RDS provides a range of services including data profiling, mapping, transformation, validation, ingestion, and dissemination. For more information about each of these APIs and how you can incorporate or consume them as part of your work flow please visit the MTNA website.
@@ -18,7 +21,7 @@
Make RDS queries easy. Write strongly typed code. Use RDS-JS.
## References
-[RDS SDK Documentation](https://mtna.github.io/rds-js/) | [RDS API Documentation](https://covid19.richdataservices.com/rds/swagger/) | [Examples](https://github.com/mtna/rds-js-examples) | [Contributing](CONTRIBUTING.md) | [Developer Documentation](DEVELOPER.md) | [Changelog](https://github.com/mtna/rds-js/releases)
+[RDS SDK Documentation][docs] | [RDS API Documentation](https://covid19.richdataservices.com/rds/swagger/) | [Examples][examples] | [Contributing](CONTRIBUTING.md) | [Developer Documentation](DEVELOPER.md) | [Changelog](https://github.com/mtna/rds-js/releases)
|---|---|---|---|---|---|
## Quick start
@@ -31,46 +34,76 @@ Install the sdk into your project.
npm install @rds/sdk
```
-#### Initialization
-
-Import `RdsServer` and initialize to indicate where the RDS API is hosted. This must be done a single time before performing any queries.
+### The setup
```typescript
-import { RdsServer } from '@rds/sdk';
-RdsServer.init('https://', 'covid19.richdataservices.com');
+import { RdsServer, RdsCatalog, RdsDataProduct } from '@rds/sdk';
+
+// Instantiate a new server to define where the RDS API is hosted.
+const server = new RdsServer('https://covid19.richdataservices.com/rds');
+// Instantiate a catalog that exists on the server
+const catalog = new RdsCatalog(server, 'int');
+// Instantiate a data product that exists on the catalog
+const dataProduct = new RdsDataProduct(catalog, 'jhu_country');
```
-### RDS Query Controller
+These are the basic, foundational building blocks of the RDS SDK. From here, we can explore what catalogs/data products exist on the server, details about them, subset the data through various queries, and downloading customized data packages.
-This service is used to query data products for both record level and aggregate data.
+See the [documentation][docs] for the full SDK API.
-#### Count
+---
-> Get the number of records in a dataset
+### RdsServer
-```typescript
-import { HttpResponse, RdsQueryController } from '@rds/sdk';
+Represents a single RDS API server, provides methods to query server-level information.
+
+> Get the root catalog on the server
+```ts
+import { RdsServer } from '@rds/sdk';
+const server = new RdsServer('https://covid19.richdataservices.com/rds');
+server
+ .getRootCatalog()
+ .then(res=>
+ console.log(`There are ${res.parsedBody.catalogs.length} catalogs on this server!`)
+ );
+```
-const CATALOG_ID = 'covid19';
-const DATA_PRODUCT_ID = 'us_jhu_ccse_country';
+---
-RdsQueryController
- .count(CATALOG_ID, DATA_PRODUCT_ID)
- .then((res: HttpResponse) =>
- { console.log(`Found ${res.parsedBody} records!`); }
+### RdsCatalog
+
+Represents a single catalog on a server, provides methods to query catalog related information.
+
+> Resolve properties about the catalog
+```ts
+import { RdsCatalog } from '@rds/sdk';
+// Given a previously instantiated server, like in the examples above
+const catalog = new RdsCatalog(server, 'int');
+catalog
+ .resolve()
+ .then(()=>
+ catalog.name; // Name of catalog
+ catalog.description; // Catalog description
+ catalog.dataProducts; // All the data products on this catalog
+ // See the docs for all the possible properties
);
```
-#### Select
+---
-> Running a select query on the specified data product returns record level microdata.
+### RdsDataProduct
-```typescript
-import { AmchartsDataSet, HttpResponse, RdsQueryController, RdsSelectParameters } from '@rds/sdk';
+Represents a single data product within a catalog, provides methods to query data product related information.
+
+> Run a **select** query to get record level microdata.
-const CATALOG_ID = 'covid19';
-const DATA_PRODUCT_ID = 'us_jhu_ccse_country';
-const PARAMS: RdsSelectParameters = {
+```ts
+import { AmchartsDataSet, HttpResponse, RdsDataProduct, RdsSelectParameters } from '@rds/sdk';
+
+// Given the catalog from the above examples
+const dataProduct = new RdsDataProduct(catalog, 'jhu_country');
+// Specify some parameters
+const params: RdsSelectParameters = {
cols: 'date_stamp,cnt_confirmed,cnt_death,cnt_recovered',
where: '(iso3166_1=US)',
metadata: true,
@@ -78,33 +111,38 @@ const PARAMS: RdsSelectParameters = {
format: 'amcharts'
};
-RdsQueryController
- .select(CATALOG_ID, DATA_PRODUCT_ID, PARAMS)
+dataProduct
+ .select(params)
.then((res: HttpResponse) =>
- { /** Make a cool visualization */ }
+ { /* Make a cool visualization */ }
);
```
-#### Tabulate
-
-> Running tabulations on the specified data product returns aggregate level data about the dimensions and measures specified.
+> Run a **tabulation** to get aggregate level data about the dimensions and measures specified.
```typescript
-import { AmchartsDataSet, HttpResponse, RdsQueryController, RdsTabulateParameters } from '@rds/sdk';
-
-const CATALOG_ID = 'covid19';
-const DATA_PRODUCT_ID = 'us_jhu_ccse_country';
-const PARAMS: RdsTabulateParameters = {
- dims: 'iso3166_1',
- measure: 'cnt_confirmed:SUM(cnt_confirmed),cnt_death:SUM(cnt_death),cnt_recovered:SUM(cnt_recovered)',
- orderby: 'cnt_confirmed DESC',
+import { PlotlyDataSet, HttpResponse, RdsDataProduct, RdsTabulateParameters } from '@rds/sdk';
+
+// Given the catalog from the above examples
+const dataProduct = new RdsDataProduct(catalog, 'jhu_country');
+// Specify some parameters
+const params: RdsTabulateParameters = {
+ dims: 'date_stamp,iso3166_1',
+ measure: 'cnt_confirmed:SUM(cnt_confirmed)',
+ where: '(year_stamp=2020) AND (iso3166_1=US OR iso3166_1=CA OR iso3166_1=ES OR iso3166_1=IT OR iso3166_1=CN)',
+ orderby: 'date_stamp ASC,iso3166_1 ASC',
metadata: true,
- limit: 10
+ inject: true,
+ totals: true,
+ format: 'plotly_heatmap'
};
-RdsQueryController
- .tabulate(CATALOG_ID, DATA_PRODUCT_ID, PARAMS)
- .then((res: HttpResponse) =>
- { /** Make a cool visualization */ }
+dataProduct
+ .tabulate(params)
+ .then((res: HttpResponse) =>
+ { /* Make a cool visualization */ }
);
```
+
+[docs]: https://mtna.github.io/rds-js/
+[examples]: https://github.com/mtna/rds-js-examples
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index e134842..b003af5 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3492,6 +3492,37 @@
"rimraf": "^2.5.2"
}
},
+ "@mtna/model-base-ui": {
+ "version": "9.0.6",
+ "resolved": "https://registry.npmjs.org/@mtna/model-base-ui/-/model-base-ui-9.0.6.tgz",
+ "integrity": "sha512-TFBKZcbSLU6FG9BuUz7pCdxWbDgvpvwmJsGjCBOPr7UcUCW2n3KNTnCe6loi+BOAB0wYLY4yZQn7ht8wxdu+SA=="
+ },
+ "@mtna/model-core-ui": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/@mtna/model-core-ui/-/model-core-ui-10.0.0.tgz",
+ "integrity": "sha512-UFCpybNNksQfrnwY1hYtNiBgceBUr4gGJXG0r/pnFPcUXECeAzHSwO6yQjrYL6ORqKwpRTLZP1CJ5XU5FB8Www=="
+ },
+ "@mtna/model-predefined-data-ui": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@mtna/model-predefined-data-ui/-/model-predefined-data-ui-1.1.6.tgz",
+ "integrity": "sha512-7PhCGJ0aCXrmT05T2VhX75CJtyYKlsxy11ZEdpemBDqEdX6lwSqN5amda0LtbdiiQ/AMuir/oiOyNz7bOZF7UA=="
+ },
+ "@mtna/pojo-base-ui": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/@mtna/pojo-base-ui/-/pojo-base-ui-9.0.2.tgz",
+ "integrity": "sha512-YVMR3bRYjNpB+zdfc4yVejkgeHm1+/YbuGVgtdsW79fUtM/Tgfa2oSDRhU3CQ3lCPbxeMsSzqi47N9L/z9LXwA==",
+ "requires": {
+ "tslib": "^1.10.0"
+ }
+ },
+ "@mtna/pojo-consumer-ui": {
+ "version": "1.1.9",
+ "resolved": "https://registry.npmjs.org/@mtna/pojo-consumer-ui/-/pojo-consumer-ui-1.1.9.tgz",
+ "integrity": "sha512-hLvoH07w/l3+i2SmD/pym+jfuD9i1/Q2wSfwkSGImQ1j6s/pI1FBx356b1Azqd/ZXTOy4yLhxTPHxaH2zRjjrg==",
+ "requires": {
+ "tslib": "^1.10.0"
+ }
+ },
"@mtna/prettier-config-ui": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@mtna/prettier-config-ui/-/prettier-config-ui-1.0.1.tgz",
@@ -6863,6 +6894,16 @@
"cross-spawn": "^6.0.5"
}
},
+ "cross-fetch": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.0.4.tgz",
+ "integrity": "sha512-MSHgpjQqgbT/94D4CyADeNoYh52zMkCX4pcJvPP5WqPsLFMKjr2TCMg381ox5qI0ii2dPwaLx/00477knXqXVw==",
+ "dev": true,
+ "requires": {
+ "node-fetch": "2.6.0",
+ "whatwg-fetch": "3.0.0"
+ }
+ },
"cross-spawn": {
"version": "6.0.5",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
@@ -10540,6 +10581,16 @@
"jest-util": "^26.0.1"
}
},
+ "jest-fetch-mock": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/jest-fetch-mock/-/jest-fetch-mock-3.0.3.tgz",
+ "integrity": "sha512-Ux1nWprtLrdrH4XwE7O7InRY6psIi3GOsqNESJgMJ+M5cv4A8Lh7SN9d2V2kKRZ8ebAfcd1LNyZguAOb6JiDqw==",
+ "dev": true,
+ "requires": {
+ "cross-fetch": "^3.0.4",
+ "promise-polyfill": "^8.1.3"
+ }
+ },
"jest-get-type": {
"version": "26.0.0",
"resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-26.0.0.tgz",
@@ -19252,6 +19303,12 @@
"asap": "~2.0.3"
}
},
+ "promise-polyfill": {
+ "version": "8.1.3",
+ "resolved": "https://registry.npmjs.org/promise-polyfill/-/promise-polyfill-8.1.3.tgz",
+ "integrity": "sha512-MG5r82wBzh7pSKDRa9y+vllNHz3e3d4CNj1PQE4BQYxLme0gKYYBm9YENq+UkEikyZ0XbiGWxYlVw3Rl9O/U8g==",
+ "dev": true
+ },
"prompt": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/prompt/-/prompt-1.0.0.tgz",
@@ -23251,6 +23308,12 @@
"iconv-lite": "0.4.24"
}
},
+ "whatwg-fetch": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.0.0.tgz",
+ "integrity": "sha512-9GSJUgz1D4MfyKU7KRqwOjXCXTqWdFNvEr7eUBYchQiVc744mqK/MzXPNR2WsPkmkOa4ywfg8C2n8h+13Bey1Q==",
+ "dev": true
+ },
"whatwg-mimetype": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz",
diff --git a/package.json b/package.json
index 06c2559..c605103 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,11 @@
"prepare": "npm run snyk-protect"
},
"dependencies": {
+ "@mtna/model-base-ui": "^9.0.6",
+ "@mtna/model-core-ui": "^10.0.0",
+ "@mtna/model-predefined-data-ui": "^1.1.6",
+ "@mtna/pojo-base-ui": "^9.0.2",
+ "@mtna/pojo-consumer-ui": "^1.1.9",
"@types/google.visualization": "0.0.52",
"snyk": "^1.321.0"
},
@@ -68,6 +73,7 @@
"husky": "^1.0.1",
"jest": "^26.0.1",
"jest-config": "^26.0.1",
+ "jest-fetch-mock": "^3.0.3",
"lint-staged": "^8.0.0",
"lodash.camelcase": "^4.3.0",
"prettier": "^1.14.3",
@@ -111,7 +117,7 @@
"transform": {
".(ts|tsx)": "ts-jest"
},
- "testEnvironment": "node",
+ "testEnvironment": "jsdom",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
@@ -132,6 +138,9 @@
},
"collectCoverageFrom": [
"src/*.{js,ts}"
+ ],
+ "setupFiles": [
+ "./tools/setupJest.js"
]
},
"prettier": "@mtna/prettier-config-ui",
diff --git a/resources/rds-logo.png b/resources/rds-logo.png
new file mode 100644
index 0000000..b65148c
Binary files /dev/null and b/resources/rds-logo.png differ
diff --git a/src/models/async/async-resource.ts b/src/models/async/async-resource.ts
new file mode 100644
index 0000000..35d610c
--- /dev/null
+++ b/src/models/async/async-resource.ts
@@ -0,0 +1,72 @@
+import { ResolutionListener } from './resolution-listener';
+
+/**
+ * An asyncronous resource that can be resolved.
+ */
+export abstract class AsyncResource {
+ /** Whether this resource is resolved */
+ private resolved = false;
+ /** Whether this resource is resolving */
+ private resolving = false;
+ /** Array of resolution listeners */
+ private resolutionListeners: ResolutionListener[] = [];
+
+ /**
+ * Create a new AsyncResource
+ *
+ * @param resolve whether to resolve the resource now, defaults to false
+ */
+ constructor(resolve: boolean) {
+ if (resolve) {
+ this.resolve().catch(error => console.error('[@rds/sdk] AsyncResource: failed to resolve', error));
+ }
+ }
+
+ /** @returns whether this resource is resolved */
+ isResolved(): boolean {
+ return this.resolved;
+ }
+
+ /** @returns whether this resource is resolving */
+ isResolving(): boolean {
+ return this.resolving;
+ }
+
+ /**
+ * Register a listener that will emit when this resource has been resolved sucessfully.
+ * @param listener the listener for when this resource has been resolved
+ */
+ registerResolutionListener(listener: ResolutionListener) {
+ this.resolutionListeners.push(listener);
+ }
+
+ /**
+ * Resolve this resource.
+ *
+ * @returns a promise that completes once the resource is resolved
+ */
+ abstract async resolve(): Promise;
+
+ /**
+ * Setter for `resolved`.
+ * @param resolved whether this resource is resolved
+ */
+ protected setResolved(resolved: boolean) {
+ this.resolved = resolved;
+ // When the resource is resolved,
+ // notify any resolution listeners
+ if (this.resolved) {
+ while (this.resolutionListeners.length) {
+ this.resolutionListeners.pop()?.resolved();
+ }
+ }
+ }
+
+ /**
+ * Setter for `resolving`.
+ * @param resolving whether the resource is resolving
+ */
+ protected setResolving(resolving: boolean) {
+ this.resolving = resolving;
+ }
+}
diff --git a/src/models/async/index.ts b/src/models/async/index.ts
new file mode 100644
index 0000000..6134d77
--- /dev/null
+++ b/src/models/async/index.ts
@@ -0,0 +1,2 @@
+export * from './async-resource';
+export * from './resolution-listener';
diff --git a/src/models/async/resolution-listener.ts b/src/models/async/resolution-listener.ts
new file mode 100644
index 0000000..b3317ec
--- /dev/null
+++ b/src/models/async/resolution-listener.ts
@@ -0,0 +1,3 @@
+export interface ResolutionListener {
+ resolved(): void;
+}
diff --git a/src/models/data-set-metadata.ts b/src/models/data-set-metadata.ts
new file mode 100644
index 0000000..656c51d
--- /dev/null
+++ b/src/models/data-set-metadata.ts
@@ -0,0 +1,6 @@
+import { Classification, RecordLayout } from '@mtna/pojo-consumer-ui';
+
+export interface DataSetMetadata {
+ recordLayout?: RecordLayout;
+ classifications?: Classification[];
+}
diff --git a/src/datasets/amcharts.ts b/src/models/datasets/amcharts.ts
similarity index 100%
rename from src/datasets/amcharts.ts
rename to src/models/datasets/amcharts.ts
diff --git a/src/datasets/formatted.ts b/src/models/datasets/formatted.ts
similarity index 100%
rename from src/datasets/formatted.ts
rename to src/models/datasets/formatted.ts
diff --git a/src/datasets/gcharts.ts b/src/models/datasets/gcharts.ts
similarity index 100%
rename from src/datasets/gcharts.ts
rename to src/models/datasets/gcharts.ts
diff --git a/src/datasets/index.ts b/src/models/datasets/index.ts
similarity index 100%
rename from src/datasets/index.ts
rename to src/models/datasets/index.ts
diff --git a/src/datasets/plotly.ts b/src/models/datasets/plotly.ts
similarity index 100%
rename from src/datasets/plotly.ts
rename to src/models/datasets/plotly.ts
diff --git a/src/models/http-response.ts b/src/models/http-response.ts
new file mode 100644
index 0000000..d2c60fd
--- /dev/null
+++ b/src/models/http-response.ts
@@ -0,0 +1,4 @@
+/** Typed http reponse */
+export interface HttpResponse extends Response {
+ parsedBody?: T;
+}
diff --git a/src/models/index.ts b/src/models/index.ts
new file mode 100644
index 0000000..5ab6df8
--- /dev/null
+++ b/src/models/index.ts
@@ -0,0 +1,7 @@
+export * from './async/index';
+export * from './data-set-metadata';
+export * from './datasets/index';
+export * from './http-response';
+export * from './parameters/index';
+export * from './parsed-url';
+export * from './server/index';
diff --git a/src/parameters/common-query.ts b/src/models/parameters/common-query.ts
similarity index 100%
rename from src/parameters/common-query.ts
rename to src/models/parameters/common-query.ts
diff --git a/src/parameters/format.ts b/src/models/parameters/format.ts
similarity index 100%
rename from src/parameters/format.ts
rename to src/models/parameters/format.ts
diff --git a/src/parameters/index.ts b/src/models/parameters/index.ts
similarity index 100%
rename from src/parameters/index.ts
rename to src/models/parameters/index.ts
diff --git a/src/parameters/select.ts b/src/models/parameters/select.ts
similarity index 100%
rename from src/parameters/select.ts
rename to src/models/parameters/select.ts
diff --git a/src/parameters/tabulate.ts b/src/models/parameters/tabulate.ts
similarity index 100%
rename from src/parameters/tabulate.ts
rename to src/models/parameters/tabulate.ts
diff --git a/src/models/parsed-url.ts b/src/models/parsed-url.ts
new file mode 100644
index 0000000..e4e706c
--- /dev/null
+++ b/src/models/parsed-url.ts
@@ -0,0 +1,24 @@
+export class ParsedUrl {
+ /**
+ * @param source the original url that was parsed
+ * @param protocol the protocol declares how your web browser should communicate with a web server when sending or fetching a web page or document.
+ * @param host the subdomain (if it exists) and domain
+ * @param port the optional port number
+ * @param path the path typically refers to a file or directory on the web server
+ * @param segments the path divided into each segment
+ * @param query is represented by a question mark followed by one or more parameters.
+ * @param params are snippets of information found in the query string of a URL. An object keyed on the parameter name and the value is the paramter value
+ * @param hash or a fragment, is an internal page reference, sometimes called a named anchor
+ */
+ constructor(
+ public source: string,
+ public protocol: string,
+ public host: string,
+ public port: string = '',
+ public path: string,
+ public segments: string[] = [],
+ public query: string = '',
+ public params: { [name: string]: string } = {},
+ public hash: string = ''
+ ) {}
+}
diff --git a/src/models/server/index.ts b/src/models/server/index.ts
new file mode 100644
index 0000000..8c67279
--- /dev/null
+++ b/src/models/server/index.ts
@@ -0,0 +1,2 @@
+export * from './information';
+export * from './rds-version';
diff --git a/src/models/server/information.ts b/src/models/server/information.ts
new file mode 100644
index 0000000..2866d3f
--- /dev/null
+++ b/src/models/server/information.ts
@@ -0,0 +1,8 @@
+export interface ServerInformation {
+ /** RDS API server name */
+ name: string;
+ /** Version number */
+ version: string;
+ /** Date the version was released */
+ released: string;
+}
diff --git a/src/models/server/rds-version.ts b/src/models/server/rds-version.ts
new file mode 100644
index 0000000..0673dfc
--- /dev/null
+++ b/src/models/server/rds-version.ts
@@ -0,0 +1,12 @@
+export interface RdsVersion {
+ /** Version number */
+ version: string;
+ /** Date the version was released */
+ released: string;
+ added: string[];
+ changed: string[];
+ deprecated: string[];
+ removed: string[];
+ fixed: string[];
+ security: string[];
+}
diff --git a/src/public_api.ts b/src/public_api.ts
index b0d4928..5f0c905 100644
--- a/src/public_api.ts
+++ b/src/public_api.ts
@@ -1,5 +1,5 @@
-export * from './datasets/index';
-export * from './parameters/index';
-export * from './rds-query-controller';
+export * from './models/index';
+export * from './rds-catalog';
+export * from './rds-data-product';
export * from './rds-server';
export * from './utils/index';
diff --git a/src/rds-catalog.spec.ts b/src/rds-catalog.spec.ts
new file mode 100644
index 0000000..328e42a
--- /dev/null
+++ b/src/rds-catalog.spec.ts
@@ -0,0 +1,98 @@
+import fetchMock from 'jest-fetch-mock';
+
+import { RdsCatalog } from './rds-catalog';
+import { RdsDataProduct } from './rds-data-product';
+import { RdsServer } from './rds-server';
+import { HttpUtil } from './utils/http';
+
+describe('RdsCatalog', () => {
+ const COVID_API_URL = 'https://covid19.richdataservices.com/rds';
+ const CATALOG_ID = 'int';
+ const server = new RdsServer(COVID_API_URL);
+
+ it('can instantiate', () => {
+ expect(new RdsCatalog(server, CATALOG_ID)).toBeInstanceOf(RdsCatalog);
+ });
+
+ describe('Constructor', () => {
+ const catalog = new RdsCatalog(server, CATALOG_ID);
+ it('should set the api url', () => {
+ expect(catalog.apiUrl).toEqual(COVID_API_URL);
+ });
+
+ it('should set the catalog url', () => {
+ expect(catalog.catalogUrl).toEqual(`${COVID_API_URL}/api/catalog/${CATALOG_ID}`);
+ });
+ });
+
+ describe('Get data product', () => {
+ it(`should create and return a new RdsDataProduct`, () => {
+ expect(new RdsCatalog(server, CATALOG_ID).getDataProduct('')).toBeInstanceOf(RdsDataProduct);
+ });
+ });
+
+ describe('Get metadata', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/catalog/{CATALOG_ID}/metadata`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const catalog = new RdsCatalog(server, CATALOG_ID);
+ expect.assertions(2);
+ return catalog.getMetadata().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/catalog/${CATALOG_ID}/metadata`);
+ spy.mockRestore();
+ });
+ });
+ });
+
+ describe(`Resolve the catalog's properties`, () => {
+ let catalog: RdsCatalog;
+ beforeEach(() => {
+ catalog = new RdsCatalog(server, CATALOG_ID);
+ });
+ it(`should set resolving to true before calling the api`, () => {
+ expect.assertions(1);
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation(
+ () =>
+ new Promise(resolve => {
+ expect(catalog.isResolving()).toBe(true);
+ resolve();
+ })
+ );
+ return catalog.resolve().then(() => {
+ spy.mockRestore();
+ });
+ });
+ it(`should set resolving to false once the api request completes`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation(() => new Promise(resolve => resolve()));
+ expect.assertions(1);
+ return catalog.resolve().then(() => {
+ expect(catalog.isResolving()).toBe(false);
+ spy.mockRestore();
+ });
+ });
+ it(`should set resolved to true when the api request completes sucessfully`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation(() => new Promise(resolve => resolve()));
+ expect.assertions(2);
+ expect(catalog.isResolved()).toBe(false);
+ return catalog.resolve().then(() => {
+ expect(catalog.isResolved()).toBe(true);
+ spy.mockRestore();
+ });
+ });
+ it(`should set the catalog's properties once the api request completes sucessfully`, () => {
+ fetchMock.mockOnce(JSON.stringify({ catalogCount: 10 }));
+ expect.assertions(1);
+ return catalog.resolve().then(() => {
+ expect(catalog.catalogCount).toBe(10);
+ });
+ });
+ it(`should throw an error when the api request fails`, () => {
+ const fakeError = new Error('fake error message');
+ fetchMock.mockRejectOnce(fakeError);
+ expect.assertions(1);
+ return catalog.resolve().catch(e => {
+ expect(e).toEqual(fakeError);
+ });
+ });
+ });
+});
diff --git a/src/rds-catalog.ts b/src/rds-catalog.ts
new file mode 100644
index 0000000..cc72738
--- /dev/null
+++ b/src/rds-catalog.ts
@@ -0,0 +1,113 @@
+import { Catalog } from '@mtna/pojo-consumer-ui';
+
+import { AsyncResource } from './models/async/async-resource';
+import { DataSetMetadata } from './models/data-set-metadata';
+import { HttpResponse } from './models/http-response';
+import { RdsDataProduct } from './rds-data-product';
+import { RdsServer } from './rds-server';
+import { HttpUtil } from './utils/http';
+
+/**
+ * An instance of a RDS Catalog.
+ * A basic building block to interact with a RDS API.
+ * Includes methods to query catalog related information.
+ *
+ * @example
+ * ```ts
+ * const covidServer = new RdsServer('https://covid19.richdataservices.com/rds');
+ * const covidCatalog = new RdsCatalog(covidServer, 'int');
+ * covidCatalog
+ * .getMetadata()
+ * .then(
+ * res => console.log('Catalog metadata:', res.parsedBody),
+ * error => console.error('Oh no!', error)
+ * );
+ * ```
+ */
+export interface RdsCatalog extends Catalog {}
+export class RdsCatalog extends AsyncResource {
+ /** The url to the RDS API */
+ get apiUrl(): string {
+ return this.server.apiUrl;
+ }
+
+ /** The url for catalog related API endpoints */
+ get catalogUrl(): string {
+ return `${this.server.apiUrl}/api/catalog/${this.catalogId}`;
+ }
+
+ /**
+ * Create a new RdsCatalog which provides
+ * methods to interact with catalog-related
+ * endpoints on the RDS API.
+ *
+ * @param server the RDS API server on which this catalog exists
+ * @param catalogId the ID of this specific catalog
+ * @param resolve whether to automatically start resolving all the catalog's own properties, defaults to false
+ */
+ constructor(protected readonly server: RdsServer, public readonly catalogId: string, resolve = false) {
+ super(resolve);
+ }
+
+ /**
+ * Create and get an instance of a RDS Data Product that exists on
+ * this RdsCatalog. This is a convenience method, these two code snippets
+ * are equivalent:
+ * ```ts
+ * const dataProduct = new RdsServer('https://covid19.richdataservices.com/rds')
+ * .getCatalog('int')
+ * .getDataProduct('jhu_country');
+ * ```
+ * and
+ * ```ts
+ * const server = new RdsServer('https://covid19.richdataservices.com/rds');
+ * const catalog = new RdsCatalog(server, 'int');
+ * const dataProduct = new RdsDataProduct(catalog, 'jhu_country');
+ * ```
+ * @param dataProductId the ID of the specific data product
+ * @param resolve whether to automatically start resolving all the data product's own properties, defaults to false
+ * @returns a new RdsDataProduct
+ */
+ getDataProduct(dataProductId: string, resolve = false): RdsDataProduct {
+ return new RdsDataProduct(this, dataProductId, resolve);
+ }
+
+ /**
+ * Get catalog metadata.
+ * This will retrieve the metadata for all of the data products
+ * that are in the specified catalog. For each data product there
+ * will be a record layout with its variables along with any
+ * classifications that are referenced by the variables.
+ *
+ * @returns metadata about the specified catalog
+ */
+ async getMetadata(): Promise> {
+ return HttpUtil.get(`${this.catalogUrl}/metadata`);
+ }
+
+ /**
+ * Resolve this catalog.
+ * This allows a more specific view of a catalog and
+ * its data products, it is a subset of the root catalog
+ * and holds no additional information to what can be
+ * found in the broader get catalog endpoint.
+ *
+ * @returns a promise that completes once the catalog is resolved
+ */
+ async resolve(): Promise {
+ this.setResolving(true);
+ return new Promise((resolve, reject) => {
+ HttpUtil.get(`${this.catalogUrl}`)
+ .then((res: HttpResponse) => {
+ if (res?.parsedBody) {
+ // Assign all properties from the api response to this resource
+ Object.assign(this, res.parsedBody);
+ }
+ this.setResolved(true);
+ resolve();
+ })
+ .finally(() => this.setResolving(false))
+ .catch(error => reject(error));
+ });
+ }
+}
diff --git a/src/rds-data-product.spec.ts b/src/rds-data-product.spec.ts
new file mode 100644
index 0000000..b3b012b
--- /dev/null
+++ b/src/rds-data-product.spec.ts
@@ -0,0 +1,120 @@
+import fetchMock from 'jest-fetch-mock';
+
+import { RdsCatalog } from './rds-catalog';
+import { RdsDataProduct } from './rds-data-product';
+import { RdsServer } from './rds-server';
+import { HttpUtil } from './utils/http';
+
+describe('RdsDataProduct', () => {
+ const COVID_API_URL = 'https://covid19.richdataservices.com/rds';
+ const CATALOG_ID = 'int';
+ const DATA_PRODUCT_ID = 'jhu_country';
+ const server = new RdsServer(COVID_API_URL);
+ const catalog = new RdsCatalog(server, CATALOG_ID);
+
+ it('can instantiate', () => {
+ expect(new RdsDataProduct(catalog, DATA_PRODUCT_ID)).toBeInstanceOf(RdsDataProduct);
+ });
+
+ describe('Constructor', () => {
+ const dataProduct = new RdsDataProduct(catalog, DATA_PRODUCT_ID);
+ it('should set the api url', () => {
+ expect(dataProduct.dataProductUrl).toEqual(`${COVID_API_URL}/api/catalog/${CATALOG_ID}/${DATA_PRODUCT_ID}`);
+ });
+ it('should set the query url', () => {
+ expect(dataProduct.queryUrl).toEqual(`${COVID_API_URL}/api/query/${CATALOG_ID}/${DATA_PRODUCT_ID}`);
+ });
+ });
+
+ describe('Get the record count', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/query/{CATALOG_ID}/{DATA_PRODUCT_ID}/count`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const dataProduct = new RdsDataProduct(catalog, DATA_PRODUCT_ID);
+ expect.assertions(2);
+ return dataProduct.count().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/query/${CATALOG_ID}/${DATA_PRODUCT_ID}/count`);
+ spy.mockRestore();
+ });
+ });
+ });
+
+ describe('Run a select query', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/query/{CATALOG_ID}/{DATA_PRODUCT_ID}/select?`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const dataProduct = new RdsDataProduct(catalog, DATA_PRODUCT_ID);
+ expect.assertions(2);
+ return dataProduct.select().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/query/${CATALOG_ID}/${DATA_PRODUCT_ID}/select?`);
+ spy.mockRestore();
+ });
+ });
+ });
+
+ describe('Run a tabulation', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/query/{CATALOG_ID}/{DATA_PRODUCT_ID}/tabulate?`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const dataProduct = new RdsDataProduct(catalog, DATA_PRODUCT_ID);
+ expect.assertions(2);
+ return dataProduct.tabulate().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/query/${CATALOG_ID}/${DATA_PRODUCT_ID}/tabulate?`);
+ spy.mockRestore();
+ });
+ });
+ });
+
+ describe(`Resolve the data product's properties`, () => {
+ let dataProduct: RdsDataProduct;
+ beforeEach(() => {
+ dataProduct = new RdsDataProduct(catalog, DATA_PRODUCT_ID);
+ });
+
+ it(`should set resolving to true before calling the api`, () => {
+ expect.assertions(1);
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation(
+ () =>
+ new Promise(resolve => {
+ expect(dataProduct.isResolving()).toBe(true);
+ resolve();
+ })
+ );
+ return dataProduct.resolve().then(() => {
+ spy.mockRestore();
+ });
+ });
+ it(`should set resolving to false once the api request completes`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation(() => new Promise(resolve => resolve()));
+ expect.assertions(1);
+ return dataProduct.resolve().then(() => {
+ expect(dataProduct.isResolving()).toBe(false);
+ spy.mockRestore();
+ });
+ });
+ it(`should set resolved to true when the api request completes sucessfully`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation(() => new Promise(resolve => resolve()));
+ expect.assertions(2);
+ expect(dataProduct.isResolved()).toBe(false);
+ return dataProduct.resolve().then(() => {
+ expect(dataProduct.isResolved()).toBe(true);
+ spy.mockRestore();
+ });
+ });
+ it(`should set the data product's properties once the api request completes sucessfully`, () => {
+ fetchMock.mockOnce(JSON.stringify({ description: 'fake description' }));
+ expect.assertions(1);
+ return dataProduct.resolve().then(() => {
+ expect(dataProduct.description).toBe('fake description');
+ });
+ });
+ it(`should throw an error when the api request fails`, () => {
+ const fakeError = new Error('fake error message');
+ fetchMock.mockRejectOnce(fakeError);
+ expect.assertions(1);
+ return dataProduct.resolve().catch(e => {
+ expect(e).toEqual(fakeError);
+ });
+ });
+ });
+});
diff --git a/src/rds-data-product.ts b/src/rds-data-product.ts
new file mode 100644
index 0000000..cbf2c3a
--- /dev/null
+++ b/src/rds-data-product.ts
@@ -0,0 +1,123 @@
+import { DataProduct } from '@mtna/pojo-consumer-ui';
+
+import { AsyncResource } from './models/async/async-resource';
+import { FormattedDataSet } from './models/datasets/formatted';
+import { HttpResponse } from './models/http-response';
+import { RdsSelectParameters } from './models/parameters/select';
+import { RdsTabulateParameters } from './models/parameters/tabulate';
+import { RdsCatalog } from './rds-catalog';
+import { HttpUtil } from './utils/http';
+import { serializeRdsParameters } from './utils/url-serializers';
+
+/**
+ * An instance of a RDS Data Product.
+ * A basic building block to interact with a RDS API.
+ * Includes methods to query data product related information.
+ *
+ * @example
+ * ```ts
+ * const covidServer = new RdsServer('https://covid19.richdataservices.com/rds');
+ * const covidCatalog = new RdsCatalog(covidServer, 'int');
+ * const dataProduct = new RdsDataProduct(covidCatalog, 'jhu_country');
+ * dataProduct
+ * .select()
+ * .then(
+ * res => console.log('Data:', res.parsedBody),
+ * error => console.error('Oh no!', error)
+ * );
+ * ```
+ */
+export interface RdsDataProduct extends DataProduct {}
+export class RdsDataProduct extends AsyncResource {
+ /** The url for data product related API endpoints. */
+ get dataProductUrl(): string {
+ return `${this.catalog.catalogUrl}/${this.dataProductId}`;
+ }
+
+ /** The url for query related API endpoints for this specific data product. */
+ get queryUrl(): string {
+ return `${this.catalog.apiUrl}/api/query/${this.catalog.catalogId}/${this.dataProductId}`;
+ }
+
+ /**
+ * Create a new RdsDataProduct which provides
+ * methods to interact with data product related
+ * endpoints on the RDS API.
+ *
+ * @param catalog the RDS Catalog on which this data product exists
+ * @param dataProductId the ID of this specific data product
+ * @param resolve whether to automatically start resolving all the data products's own properties, defaults to false
+ */
+ constructor(protected readonly catalog: RdsCatalog, public readonly dataProductId: string, resolve = false) {
+ super(resolve);
+ }
+
+ /**
+ * Get data product.
+ * This shows a single data product in a catalog, there is no
+ * additional information in this call, it simply limits the
+ * scope of what is returned.
+ *
+ * @returns a promise that completes once the data product is resolved
+ */
+ async resolve(): Promise {
+ this.setResolving(true);
+ return new Promise((resolve, reject) => {
+ HttpUtil.get(`${this.dataProductUrl}`)
+ .then((res: HttpResponse) => {
+ if (res?.parsedBody) {
+ // Assign all properties from the api response to this resource
+ Object.assign(this, res.parsedBody);
+ }
+ this.setResolved(true);
+ resolve();
+ })
+ .finally(() => this.setResolving(false))
+ .catch(error => reject(error));
+ });
+ }
+
+ //#region QUERY ENDPOINTS
+
+ /**
+ * Get record count.
+ * Runs a query to count the records of the specified data product.
+ *
+ * @returns the number of records within the data product.
+ */
+ async count(): Promise> {
+ return HttpUtil.get(`${this.queryUrl}/count`);
+ }
+
+ /**
+ * Run select query.
+ * Running a select query on the specified data product returns record level microdata.
+ * A variety of querying techniques can be used to subset, compute, order, filter and format the results.
+ *
+ * @param parameters Optional parameters for an RDS select query
+ * @returns Record level microdata, the shape will vary depending on the `format` query paramter.
+ */
+ async select(parameters?: RdsSelectParameters): Promise> {
+ return HttpUtil.get(
+ `${this.queryUrl}/select?${serializeRdsParameters(parameters)}`
+ );
+ }
+
+ /**
+ * Run tabulation query.
+ * Running tabulations on the specified data product returns
+ * aggregate level data about the dimensions and measures specified.
+ * A variety of querying techniques can be used to subset, compute, order, filter and format the results.
+ *
+ * @param parameters Optional parameters for an RDS tabulate query
+ * @returns Aggregate level data about the dimensions and measures specified.
+ * The shape will vary depending on the `format` query paramter.
+ */
+ async tabulate(parameters?: RdsTabulateParameters): Promise> {
+ return HttpUtil.get(
+ `${this.queryUrl}/tabulate?${serializeRdsParameters(parameters)}`
+ );
+ }
+
+ //#endregion QUERY ENDPOINTS
+}
diff --git a/src/rds-query-controller.ts b/src/rds-query-controller.ts
deleted file mode 100644
index e8bb781..0000000
--- a/src/rds-query-controller.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { FormattedDataSet } from './datasets/formatted';
-import { RdsSelectParameters } from './parameters/select';
-import { RdsTabulateParameters } from './parameters/tabulate';
-import { RdsServer } from './rds-server';
-import { HttpResponse, HttpUtil } from './utils/http';
-import { serializeRdsParameters } from './utils/url-serializers';
-
-/**
- * Static functions to interact with the RDS API's QueryController endpoints.
- */
-export class RdsQueryController {
- /** Base url for the RDS Query Controller */
- protected static get queryUrl(): string {
- return `${RdsServer.getInstance().apiUrl}/query`;
- }
-
- /**
- * Get record count.
- * Runs a query to count the records of the specified data product.
- *
- * @param catalogId The ID of the catalog that contains the data product.
- * @param dataProductId The ID of the data product to query.
- * @returns the number of records within the data product.
- */
- static async count(catalogId: string, dataProductId: string): Promise> {
- return HttpUtil.get(`${this.queryUrl}/${catalogId}/${dataProductId}/count`);
- }
-
- /**
- * Run select query.
- * Running a select query on the specified data product returns record level microdata.
- * A variety of querying techniques can be used to subset, compute, order, filter and format the results.
- *
- * @param catalogId The ID of the catalog that contains the data product.
- * @param dataProductId The ID of the data product to query.
- * @param parameters Optional parameters for an RDS select query
- * @returns Record level microdata, the shape will vary depending on the `format` query paramter.
- */
- static async select(
- catalogId: string,
- dataProductId: string,
- parameters?: RdsSelectParameters
- ): Promise> {
- return HttpUtil.get(`${this.queryUrl}/${catalogId}/${dataProductId}/select?${serializeRdsParameters(parameters)}`);
- }
-
- /**
- * Run tabulation query.
- * Running tabulations on the specified data product returns
- * aggregate level data about the dimensions and measures specified.
- * A variety of querying techniques can be used to subset, compute, order, filter and format the results.
- *
- * @param catalogId The ID of the catalog that contains the data product.
- * @param dataProductId The ID of the data product to query.
- * @param parameters Optional parameters for an RDS tabulate query
- * @returns Aggregate level data about the dimensions and measures specified.
- * The shape will vary depending on the `format` query paramter.
- */
- static async tabulate(
- catalogId: string,
- dataProductId: string,
- parameters?: RdsTabulateParameters
- ): Promise> {
- return HttpUtil.get(`${this.queryUrl}/${catalogId}/${dataProductId}/tabulate?${serializeRdsParameters(parameters)}`);
- }
-}
diff --git a/src/rds-server.spec.ts b/src/rds-server.spec.ts
new file mode 100644
index 0000000..3e02d14
--- /dev/null
+++ b/src/rds-server.spec.ts
@@ -0,0 +1,78 @@
+import { RdsCatalog } from './rds-catalog';
+import { RdsServer } from './rds-server';
+import { HttpUtil } from './utils/http';
+
+describe('RdsServer', () => {
+ const COVID_API_URL = 'https://covid19.richdataservices.com/rds';
+
+ it('can instantiate', () => {
+ expect(new RdsServer(COVID_API_URL)).toBeInstanceOf(RdsServer);
+ });
+
+ it('can instantiate via factory method', () => {
+ expect(RdsServer.fromUrlParts('https', 'covis19.richdataservices.com', '/rds')).toBeInstanceOf(RdsServer);
+ });
+
+ describe('Constructor', () => {
+ it('should set the api url', () => {
+ const server = new RdsServer(COVID_API_URL);
+ expect(server.apiUrl).toEqual(COVID_API_URL);
+ });
+
+ it('should parse the url into partials', () => {
+ const server = new RdsServer(COVID_API_URL);
+ expect(server.parsedUrl).toBeDefined();
+ expect(server.parsedUrl.protocol).toEqual('https');
+ expect(server.parsedUrl.host).toEqual('covid19.richdataservices.com');
+ expect(server.parsedUrl.path).toEqual('/rds');
+ });
+
+ it('should remove trailing slashes from the url', () => {
+ const server = new RdsServer(`${COVID_API_URL}/`);
+ expect(server.parsedUrl.source).toEqual(COVID_API_URL);
+ expect(server.apiUrl).toEqual(COVID_API_URL);
+ });
+ });
+
+ describe('Get catalog', () => {
+ it(`should create and return a new RdsCatalog`, () => {
+ expect(new RdsServer(COVID_API_URL).getCatalog('')).toBeInstanceOf(RdsCatalog);
+ });
+ });
+
+ describe('Get changelog', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/server/changelog`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const server = new RdsServer(COVID_API_URL);
+ return server.getChangelog().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/server/changelog`);
+ spy.mockRestore();
+ });
+ });
+ });
+
+ describe('Get info', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/server/info`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const server = new RdsServer(COVID_API_URL);
+ return server.getInfo().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/server/info`);
+ spy.mockRestore();
+ });
+ });
+ });
+
+ describe('Get root catalog', () => {
+ it(`should make an api request to ${COVID_API_URL}/api/catalog`, () => {
+ const spy = jest.spyOn(HttpUtil, 'get').mockImplementation();
+ const server = new RdsServer(COVID_API_URL);
+ return server.getRootCatalog().then(() => {
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith(`${COVID_API_URL}/api/catalog`);
+ spy.mockRestore();
+ });
+ });
+ });
+});
diff --git a/src/rds-server.ts b/src/rds-server.ts
index 2e468ab..b4a3c11 100644
--- a/src/rds-server.ts
+++ b/src/rds-server.ts
@@ -1,41 +1,128 @@
+import { Catalog } from '@mtna/pojo-consumer-ui';
+
+import { HttpResponse } from './models/http-response';
+import { ParsedUrl } from './models/parsed-url';
+import { RdsVersion } from './models/server';
+import { ServerInformation } from './models/server/information';
+import { RdsCatalog } from './rds-catalog';
+import { HttpUtil } from './utils/http';
+import { _parseUrl } from './utils/url-parser';
+
/**
- * Singleton class that holds the RDS API server information.
- * Initialization required in order to use the sdk.
+ * An instance of a RDS API server.
+ * A basic building block to interact with a RDS API.
+ * Includes methods to query server-level information.
+ *
+ * @example
+ * ```ts
+ * const covidServer = new RdsServer('https://covid19.richdataservices.com/rds');
+ * covidServer
+ * .getInfo()
+ * .then((res: HttpResponse) =>
+ * { console.log('Server info:', res.parsedBody); }
+ * );
+ * ```
*/
export class RdsServer {
- private static instance: RdsServer;
-
- /** @returns the RDS API url */
- get apiUrl(): string {
- return `${this.protocol}${this.domain}${this.port ? ':' + this.port : ''}${this.path}/api`;
+ /**
+ * Factory method for instantiating an RdsServer
+ * from the individual url parts.
+ *
+ * @example
+ * ```ts
+ * const server = RdsServer.fromUrlParts('https://','covid19.richdataservices.com', '/rds');
+ * ```
+ *
+ * @param protocol The protocol used on the site the RDS API is hosted, defaults to 'https'
+ * @param domain The domain under which the RDS API is hosted, i.e. 'covid19.richdataservices.com'
+ * @param path The path where the RDS API is hosted, defaults to '/rds'
+ * @param port Optional port where the RDS API is hosted, or undefined if not applicable
+ *
+ * @returns a new RdsServer
+ */
+ static fromUrlParts(protocol = 'https', domain: string, path = '/rds', port?: string | undefined): RdsServer {
+ return new this(`${protocol}://${domain}${port ? ':' + port : ''}${path}`);
}
- private constructor(private protocol: string, private domain: string, private port: string | undefined, private path: string) {}
+ /** The base url to the RDS API, i.e. `https://covid19.richdataservices.com/rds` */
+ readonly apiUrl: string;
+ /** The url parsed out into its partials */
+ readonly parsedUrl: ParsedUrl;
- public static getInstance(): RdsServer {
- if (!RdsServer.instance) {
- throw new Error('RdsServer has not been initialized. You must call init before getting the instance.');
- }
+ /** The url for the server related API endpoints */
+ get serverUrl(): string {
+ return `${this.apiUrl}/api/server`;
+ }
- return RdsServer.instance;
+ /**
+ * Create a new instance of a RDS API Server.
+ * @param url The full URL to the RDS API, i.e. `https://covid19.richdataservices.com/rds`
+ */
+ constructor(url: string) {
+ // Remove any trailing slashes
+ // and parse url
+ this.parsedUrl = _parseUrl(url.replace(/\/+$/, ''));
+ // Construct the api url
+ this.apiUrl = `${this.parsedUrl.protocol}://${this.parsedUrl.host}${this.parsedUrl.port ? ':' + this.parsedUrl.port : ''}${
+ this.parsedUrl.path
+ }`;
}
/**
- * Initialize the RDS server once to configure where the RDS API instance is hosted.
+ * Create and get an instance of a RDS Catalog that exists on
+ * this RdsServer. This is a convenience method, these two code snippets
+ * are equivalent:
+ * ```ts
+ * const catalog = new RdsServer('https://covid19.richdataservices.com/rds')
+ * .getCatalog('int');
+ * ```
+ * and
+ * ```ts
+ * const server = new RdsServer('https://covid19.richdataservices.com/rds');
+ * const catalog = new RdsCatalog(server, 'int');
+ * ```
+ * @param catalogId the ID of the specific catalog
+ * @param resolve whether to automatically start resolving all the catalog's own properties, defaults to false
+ * @returns a new RdsCatalog
+ */
+ getCatalog(catalogId: string, resolve = false): RdsCatalog {
+ return new RdsCatalog(this, catalogId, resolve);
+ }
+
+ /**
+ * Get changelog.
+ * Shows the change log of RDS providing version information about
+ * additions, changes, deprecations, fixed bugs, removals, and security enhancements.
*
- * @param protocol The protocol used on the site the RDS API is hosted, defaults to 'https://'
- * @param domain The domain under which the RDS API is hosted, defaults to 'covid19.richdataservices.com'
- * @param port Optional port where the RDS API is hosted, or undefined if not applicable
- * @param path The path where the RDS API is hosted, defaults to '/rds'
- * @returns the initialized `RdsServer` instance.
+ * @returns an array of information about each version and the changes between them.
*/
- public static init(protocol = 'https://', domain = 'covid19.richdataservices.com', port?: string | undefined, path = '/rds'): RdsServer {
- if (RdsServer.instance) {
- throw new Error('The RdsServer can only be initialized once.');
- }
+ async getChangelog(): Promise> {
+ return HttpUtil.get(`${this.serverUrl}/changelog`);
+ }
- RdsServer.instance = new RdsServer(protocol, domain, port, path);
+ /**
+ * Get server information.
+ * Provides the server information for RDS.
+ *
+ * @returns information about the RDS Server
+ */
+ async getInfo(): Promise> {
+ return HttpUtil.get(`${this.serverUrl}/info`);
+ }
- return RdsServer.instance;
+ /**
+ * Get the root catalog of the system.
+ * This will hold a list of all the catalogs and data products
+ * that are available on this server. This would ideally be
+ * used to power an entry point into an application.
+ * The catalog provides a starting point for users to view
+ * what is available to them and drill down into a catalog
+ * or data product of their interest. The catalogs and products
+ * may have descriptive metadata on them that is useful to display.
+ *
+ * @returns the root catalog of the RDS server
+ */
+ async getRootCatalog(): Promise> {
+ return HttpUtil.get(`${this.apiUrl}/api/catalog`);
}
}
diff --git a/src/utils/http.ts b/src/utils/http.ts
index 38c9b95..75bbbe1 100644
--- a/src/utils/http.ts
+++ b/src/utils/http.ts
@@ -1,7 +1,4 @@
-/** Typed http reponse */
-export interface HttpResponse extends Response {
- parsedBody?: T;
-}
+import { HttpResponse } from '../models/http-response';
/**
* Utility to make strongly typed HTTP requests.
diff --git a/src/utils/index.ts b/src/utils/index.ts
index 83c3a57..42e1b64 100644
--- a/src/utils/index.ts
+++ b/src/utils/index.ts
@@ -1,2 +1,3 @@
export * from './http';
+export * from './url-parser';
export * from './url-serializers';
diff --git a/src/utils/url-parser.ts b/src/utils/url-parser.ts
new file mode 100644
index 0000000..701330e
--- /dev/null
+++ b/src/utils/url-parser.ts
@@ -0,0 +1,59 @@
+import { ParsedUrl } from '../models/parsed-url';
+
+/**
+ * This function creates a new anchor element and uses location
+ * properties (inherent) to get the desired URL data. Some String
+ * operations are used (to normalize results across browsers).
+ *
+ * @remarks
+ * References JS implementation from
+ *
+ * @example
+ * ```ts
+ * const myURL = _parseUrl('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
+ * myURL.source; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
+ * myURL.protocol; // = 'http'
+ * myURL.host; // = 'abc.com'
+ * myURL.port; // = '8080'
+ * myURL.path; // = '/dir/index.html'
+ * myURL.segments; // = Array = ['dir', 'index.html']
+ * myURL.query; // = '?id=255&m=hello'
+ * myURL.params; // = Object = { id: 255, m: hello }
+ * myURL.hash; // = 'top'
+ * ```
+ *
+ * @param url the url to parse
+ * @returns the parsed url
+ */
+export function _parseUrl(url: string): ParsedUrl {
+ const a = document.createElement('a');
+ a.href = url;
+
+ const parsedUrl = new ParsedUrl(
+ url,
+ a.protocol.replace(':', ''),
+ a.hostname,
+ a.port,
+ a.pathname.replace(/^([^/])/, '/$1'),
+ a.pathname.replace(/^\//, '').split('/'),
+ a.search,
+ (function() {
+ const params: { [name: string]: string } = {};
+ const seg = a.search.replace(/^\?/, '').split('&');
+
+ for (let i = 0; i < seg.length; i++) {
+ if (!seg[i]) {
+ continue;
+ }
+ const s = seg[i].split('=');
+ params[s[0]] = s[1];
+ }
+ return params;
+ })(),
+ a.hash.replace('#', '')
+ );
+
+ // Clean up and remove anchor element
+ a.remove();
+ return parsedUrl;
+}
diff --git a/src/utils/url-serializers.ts b/src/utils/url-serializers.ts
index 2d66951..62ee0df 100644
--- a/src/utils/url-serializers.ts
+++ b/src/utils/url-serializers.ts
@@ -1,5 +1,5 @@
-import { RdsSelectParameters } from '../parameters/select';
-import { RdsTabulateParameters } from '../parameters/tabulate';
+import { RdsSelectParameters } from '../models/parameters/select';
+import { RdsTabulateParameters } from '../models/parameters/tabulate';
/**
* Serialize a parameter that has an array of values into a url query parameter.
diff --git a/test/rds-server.spec.ts b/test/rds-server.spec.ts
deleted file mode 100644
index 4b0c5c5..0000000
--- a/test/rds-server.spec.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { RdsServer } from '../src/rds-server';
-
-// TODO write some tests :)
-describe('RdsServer', () => {
- it('Can get an instance after initialized', () => {
- RdsServer.init();
- expect(RdsServer.getInstance()).toBeInstanceOf(RdsServer);
- });
-});
diff --git a/tools/setupJest.js b/tools/setupJest.js
new file mode 100644
index 0000000..d36d111
--- /dev/null
+++ b/tools/setupJest.js
@@ -0,0 +1 @@
+require('jest-fetch-mock').enableMocks();