@dimo-network/data-sdk 1.2.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.
Files changed (70) hide show
  1. package/.credentials.json.example +5 -0
  2. package/.eslintrc.json +20 -0
  3. package/.github/workflows/npm-publish.yml +42 -0
  4. package/CONTRIBUTING.md +82 -0
  5. package/LICENSE +76 -0
  6. package/README.md +216 -0
  7. package/dist/api/Method.d.ts +2 -0
  8. package/dist/api/Method.js +136 -0
  9. package/dist/api/Method.test.d.ts +1 -0
  10. package/dist/api/Method.test.js +67 -0
  11. package/dist/api/Resource.d.ts +11 -0
  12. package/dist/api/Resource.js +20 -0
  13. package/dist/api/functions/getToken.d.ts +7 -0
  14. package/dist/api/functions/getToken.js +20 -0
  15. package/dist/api/functions/index.d.ts +3 -0
  16. package/dist/api/functions/index.js +3 -0
  17. package/dist/api/functions/signChallenge.d.ts +5 -0
  18. package/dist/api/functions/signChallenge.js +8 -0
  19. package/dist/api/index.d.ts +1 -0
  20. package/dist/api/index.js +1 -0
  21. package/dist/api/resources/Attestation/index.d.ts +5 -0
  22. package/dist/api/resources/Attestation/index.js +21 -0
  23. package/dist/api/resources/Auth/index.d.ts +5 -0
  24. package/dist/api/resources/Auth/index.js +42 -0
  25. package/dist/api/resources/DeviceDefinitions/index.d.ts +5 -0
  26. package/dist/api/resources/DeviceDefinitions/index.js +29 -0
  27. package/dist/api/resources/Devices/index.d.ts +5 -0
  28. package/dist/api/resources/Devices/index.js +154 -0
  29. package/dist/api/resources/DimoRestResources.d.ts +9 -0
  30. package/dist/api/resources/DimoRestResources.js +9 -0
  31. package/dist/api/resources/TokenExchange/index.d.ts +5 -0
  32. package/dist/api/resources/TokenExchange/index.js +20 -0
  33. package/dist/api/resources/Trips/index.d.ts +5 -0
  34. package/dist/api/resources/Trips/index.js +16 -0
  35. package/dist/api/resources/Valuations/index.d.ts +5 -0
  36. package/dist/api/resources/Valuations/index.js +23 -0
  37. package/dist/api/resources/VehicleSignalDecoding/index.d.ts +5 -0
  38. package/dist/api/resources/VehicleSignalDecoding/index.js +59 -0
  39. package/dist/constants.d.ts +11 -0
  40. package/dist/constants.js +10 -0
  41. package/dist/dimo.d.ts +17 -0
  42. package/dist/dimo.js +68 -0
  43. package/dist/dimo.test.d.ts +1 -0
  44. package/dist/dimo.test.js +57 -0
  45. package/dist/environments/index.d.ts +33 -0
  46. package/dist/environments/index.js +32 -0
  47. package/dist/errors/DimoError.d.ts +9 -0
  48. package/dist/errors/DimoError.js +27 -0
  49. package/dist/errors/index.d.ts +1 -0
  50. package/dist/errors/index.js +1 -0
  51. package/dist/graphql/Query.d.ts +2 -0
  52. package/dist/graphql/Query.js +104 -0
  53. package/dist/graphql/Query.test.d.ts +1 -0
  54. package/dist/graphql/Query.test.js +47 -0
  55. package/dist/graphql/Resource.d.ts +16 -0
  56. package/dist/graphql/Resource.js +29 -0
  57. package/dist/graphql/index.d.ts +1 -0
  58. package/dist/graphql/index.js +1 -0
  59. package/dist/graphql/resources/DimoGraphqlResources.d.ts +3 -0
  60. package/dist/graphql/resources/DimoGraphqlResources.js +3 -0
  61. package/dist/graphql/resources/Identity/index.d.ts +6 -0
  62. package/dist/graphql/resources/Identity/index.js +100 -0
  63. package/dist/graphql/resources/Telemetry/index.d.ts +5 -0
  64. package/dist/graphql/resources/Telemetry/index.js +39 -0
  65. package/dist/index.d.ts +18 -0
  66. package/dist/index.js +18 -0
  67. package/dist/streamr/index.d.ts +0 -0
  68. package/dist/streamr/index.js +51 -0
  69. package/jest.config.js +16 -0
  70. package/package.json +43 -0
@@ -0,0 +1,5 @@
1
+ {
2
+ "client_id": "",
3
+ "private_key": "",
4
+ "redirect_uri": ""
5
+ }
package/.eslintrc.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "env": {
3
+ "browser": true,
4
+ "es2021": true
5
+ },
6
+ "extends": [
7
+ "airbnb-base",
8
+ "prettier/@typescript-eslint"
9
+ ],
10
+ "parser": "@typescript-eslint/parser",
11
+ "parserOptions": {
12
+ "ecmaVersion": "latest",
13
+ "sourceType": "module"
14
+ },
15
+ "plugins": [
16
+ "@typescript-eslint"
17
+ ],
18
+ "rules": {
19
+ }
20
+ }
@@ -0,0 +1,42 @@
1
+ # This workflow will run tests using node and then publish a package to GitHub Packages when a release is published
2
+ # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
+
4
+ name: Publish Package to npm
5
+
6
+ on:
7
+ release:
8
+ types: [published]
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-node@v3
16
+ with:
17
+ node-version: 20
18
+ - run: npm ci
19
+ - run: npm test
20
+ - name: Run build
21
+ run: npm run build
22
+ - name: Check dist directory
23
+ run: ls dist/
24
+
25
+ publish-npm:
26
+ needs: build
27
+ runs-on: ubuntu-latest
28
+ steps:
29
+ - uses: actions/checkout@v4
30
+ - uses: actions/setup-node@v3
31
+ with:
32
+ node-version: 20
33
+ registry-url: https://registry.npmjs.org/
34
+ - run: npm ci
35
+ - run: npm test
36
+ - name: Run build
37
+ run: npm run build
38
+ - name: Check dist directory
39
+ run: ls dist/
40
+ - run: npm publish --access public
41
+ env:
42
+ NODE_AUTH_TOKEN: ${{secrets.npm_token}}
@@ -0,0 +1,82 @@
1
+ # Contributing to DIMO SDK
2
+ Thank you for your interest in contributing to the DIMO Hello World repository! We're excited to collaborate with the community to expand the collection of examples showcasing the diverse capabilities of DIMO's platform, including our REST API, Streamr integration, GraphQL API, and more.
3
+
4
+ ## REST API Resource Data Structure
5
+ In the SDK, each `functionName` maps to a specific path for an API endpoint, the `method` will be passed in the corresponding HTTP calls. The SDK supports CRUD operations for a REST API but also includes a `FUNCTION` method to call utility functions. Add `queryParams`, `body`, `headers`, `auth`, and `return` according to how the endpoint behaves.
6
+
7
+ - `body` and `queryParams`, : Sets the requirements for body or query parameters. Anything that is marked `true` will be required, whereas `false` marks it as optional. You can also pass in a fixed strings for constants. To source the value of one query parameter from another query parameter, you can simply prepend a `$` (i.e. `queryParam3: '$queryParam1'` fixes queryParam3 to whatever is passed in by the user in queryParam1).
8
+ - `headers`: Dynamically inserts header key-value pair, this is typically used when the endpoint accepts a specific header.
9
+ - `auth`: This defines whether the endpoint requires a `access_token` or a `privilege_token`.
10
+ - `return`: This defines what the endpoint returns for a more user-friendly experience. Only Auth endpoints will return `access_token`, and Token Exchange endpoint will return `privilege_token`. **You will likely not use this at all**.
11
+
12
+ ```js
13
+ <functionName>: {
14
+ method: '<GET|POST|PUT|PATCH|DELETE|FUNCTION>',
15
+ path: '/<path>/:pathParameters' || '<functionName>',
16
+ queryParams: {
17
+ 'queryParam1': false,
18
+ 'queryParam2': true,
19
+ 'queryParam3': '<queryParamValue>' || '<$queryParam1>'
20
+ },
21
+ body: {
22
+ 'bodyParam1': false,
23
+ 'bodyParam2': true,
24
+ 'bodyParam3': '<bodyValue>'
25
+ },
26
+ headers: {
27
+ 'headerKey': '<headerValue>'
28
+ },
29
+ auth: '<web3|privilege>',
30
+ return: '<web3|privilege>'
31
+ }
32
+ ```
33
+
34
+ ## GraphQL API Resource Data Structure
35
+ Similarly in GraphQL, each `queryName` maps to a specific query that is pre-defined in GraphQL's query language.
36
+
37
+ - `params`: Defined when user inputs are required in the query.
38
+ - `query`: Outlines the query structure, and specifies where each defined `params` will be injected (at where `$` is prepended).
39
+
40
+ ```js
41
+ <queryName>: {
42
+ params: {
43
+ param1: true,
44
+ param2: true
45
+ },
46
+ query: `
47
+ <actual_graphQL_query> { input1: $param1, input2: $param2 }
48
+ `
49
+ }
50
+ ```
51
+
52
+ ## How to Contribute
53
+ Contributions can take many forms, from fixing typos in documentation to mapping new API endpoints. Here's how you can contribute:
54
+
55
+ ### Reporting Issues
56
+ If you find a bug or have a suggestion for improving an existing example, please open an issue. Be as specific as possible and include:
57
+
58
+ 1. A clear title and description
59
+ 2. Steps to reproduce the issue, if applicable
60
+ 3. Your ideas for solving the issue, if any
61
+
62
+ ### Updating API Endpoints
63
+ 1. Locate the endpoint under `/src/api/resources/<directory>/index.ts`
64
+ 2. Under the `constructor`, locate a `this.setResource()` function call
65
+ 3. Update the endpoint of interest accordingly
66
+
67
+ [Note] Some Vehicle Signal Decoding API endpoints uses `eth-addr` as one of the query parameters, for clarification and style purposes, please use `address` as the key when you pass a query parameter.
68
+
69
+ ### Updating SDK Functions
70
+ 1. Locate the functions under `/src/api/functions`
71
+ 2. Update existing functions or create new functions
72
+ 3. Export the modified function(s) in `/src/api/functions/index.ts`
73
+ 4. Locate the resource mapping under `/src/api/resources/<directory>/index.ts`
74
+ 5. Apply the new changes under `this.setResource()` function call
75
+
76
+ ### Updating GraphQL Queries
77
+ 1. Locate the queries under `/src/graphql/resources/<directory>/index.ts`
78
+ 2. Under the `constructor`, locate a `this.setQueries()` function call
79
+ 3. Update the query of interest accordingly
80
+
81
+ ### Translating the README
82
+ DIMO welcomes translation work done on the SDK.
package/LICENSE ADDED
@@ -0,0 +1,76 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
37
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
38
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
39
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
40
+
41
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
42
+
43
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
44
+
45
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
46
+
47
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
48
+
49
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
50
+
51
+ END OF TERMS AND CONDITIONS
52
+ ---
53
+
54
+ APPENDIX: How to apply the Apache License to your work.
55
+
56
+ To apply the Apache License to your work, attach the following
57
+ boilerplate notice, with the fields enclosed by brackets "[]" replaced with
58
+ your own identifying information. (Don't include the brackets!) The text
59
+ should be enclosed in the appropriate comment syntax for the file format.
60
+ We also recommend that a file or class name and description of purpose be
61
+ included on the same "printed page" as the copyright notice for easier
62
+ identification within third-party archives.
63
+
64
+ Copyright 2024 DIMO Foundation
65
+
66
+ Licensed under the Apache License, Version 2.0 (the "License");
67
+ you may not use this file except in compliance with the License.
68
+ You may obtain a copy of the License at
69
+
70
+ http://www.apache.org/licenses/LICENSE-2.0
71
+
72
+ Unless required by applicable law or agreed to in writing, software
73
+ distributed under the License is distributed on an "AS IS" BASIS,
74
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
75
+ See the License for the specific language governing permissions and
76
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,216 @@
1
+ ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/dimo-network/data-sdk/npm-publish.yml?style=flat-square)
2
+ ![GitHub top language](https://img.shields.io/github/languages/top/dimo-network/data-sdk?style=flat-square)
3
+ ![GitHub License](https://img.shields.io/github/license/dimo-network/data-sdk?style=flat-square)
4
+ [![Downloads](https://img.shields.io/npm/d18m/@dimo-network/data-sdk.svg?style=flat-square)](https://www.npmjs.com/package/@dimo-network/data-sdk)
5
+ [![Discord](https://img.shields.io/discord/892438668453740634)](https://chat.dimo.zone/)
6
+ ![X (formerly Twitter) URL](https://img.shields.io/twitter/url?url=https%3A%2F%2Ftwitter.com%2FDIMO_Network&style=social)
7
+
8
+ # DIMO Data SDK
9
+ This is an official DIMO Data SDK written in NodeJS/TypeScript. The objective of this project is to make our API more accessible to the general public.
10
+
11
+ ## Installation
12
+ Use [npm](https://www.npmjs.com/package/@dimo-network/data-sdk):
13
+ ```bash
14
+ npm install @dimo-network/data-sdk
15
+ ```
16
+
17
+ or use [yarn](https://classic.yarnpkg.com/en/package/@dimo-network/data-sdk) instead:
18
+
19
+ ```bash
20
+ yarn add @dimo-network/data-sdk
21
+ ```
22
+
23
+ ## Unit Testing
24
+ Run `npm test` or `npm run test` to execute the Jest tests.
25
+
26
+ ## API Documentation
27
+ Please visit the DIMO [Developer Documentation](https://docs.dimo.org/developer-platform) to learn more about building on DIMO and detailed information on the API.
28
+
29
+ ## How to Use the SDK
30
+
31
+ Import the SDK library:
32
+ ```ts
33
+ import { DIMO } from '@dimo-network/data-sdk';
34
+ ```
35
+
36
+ Initiate the SDK depending on the environment of your interest, we currently support both `Production` and `Dev` environments:
37
+
38
+ ```ts
39
+ const dimo = new DIMO('Production');
40
+ ```
41
+ or
42
+
43
+ ```ts
44
+ const dimo = new DIMO('Dev');
45
+ ```
46
+ ### Developer Registration
47
+ As part of the authentication process, you will need to obtain a Developer License via the [DIMO Developer Console](https://console.dimo.org/). To get started with registration, follow the steps below:
48
+ 1. Sign up on the [DIMO Developer Console](https://console.dimo.org/).
49
+ 2. Get DIMO Credits either by paying in your local currency (via Stripe) or paying with a balance (if you have one).
50
+ 3. Click on `Create app` and fill out the details about your project namespace (external-facing, e.g. `Drive2Survive LLC.`) and your application name (internal, e.g. `app-prod`)
51
+ 4. Generate an API key and add in your preferred redirect URI
52
+
53
+ ### Authentication
54
+
55
+ The SDK provides you with all the steps needed in the [Authentication Flow](https://docs.dimo.org/developer-platform/getting-started/developer-guide/authentication) to obtain an `access_token`.
56
+
57
+ #### Prerequisites for Authentication
58
+ 1. A valid Developer License
59
+ 2. A valid API key
60
+
61
+ #### API Authentication
62
+
63
+ ##### (Option 1 - PREFERRED) getToken Function
64
+ As mentioned earlier, this is the streamlined function call to directly get the `access_token`. The `address` field in challenge generation is omitted since it is essentially the `client_id` of your application per Developer License:
65
+
66
+ ```ts
67
+ const authHeader = await dimo.auth.getToken({
68
+ client_id: '<client_id>',
69
+ domain: '<domain>',
70
+ private_key: '<private_key>',
71
+ });
72
+ ```
73
+
74
+ Once you have the `authHeader`, you'll have access to the DIMO API endpoints. For endpoints that require the authorization headers, you can simply pass the results.
75
+
76
+ ```ts
77
+ // Pass the auth object to a protected endpoint
78
+ await dimo.user.get(auth);
79
+
80
+ // Pass the auth object to a protected endpoint with body parameters
81
+ await dimo.tokenexchange.exchange({
82
+ ...auth,
83
+ privileges: [4],
84
+ tokenId: <vehicle_token_id>
85
+ });
86
+
87
+ ```
88
+
89
+ ##### (Option 2) Credentials.json File
90
+ By loading a valid `.credentials.json`, you can easily call `dimo.authenticate()` if you prefer to manage your credentials differently. Instead of calling the `Auth` endpoint, you would directly interact with the SDK main class.
91
+
92
+ Start by navigating to the SDK directory that was installed, if you used NPM, you can execute `npm list -g | dimo` to find the directory. In the root directory of the SDK, there will be `.credentials.json.example` - simply remove the `.example` extension to proceed with authentication:
93
+
94
+ ```ts
95
+ // After .credentials.json are provided
96
+ const authHeader = await dimo.authenticate();
97
+ // The rest would be the same as option 1
98
+ ```
99
+
100
+ ### Querying the DIMO REST API
101
+ The SDK supports async await and your typical JS Promises. HTTP operations can be utilized in either ways:
102
+
103
+ ```ts
104
+ // Async Await
105
+ async function getAllDeviceMakes() {
106
+ try {
107
+ let response = await dimo.devicedefinitions.listDeviceMakes();
108
+ // Do something with the response
109
+ }
110
+ catch (err) { /* ... */ }
111
+ }
112
+ getAllDeviceMakes();
113
+ ```
114
+
115
+ ```js
116
+ // JS Promises
117
+ dimo.devicedefinitions.listDeviceMakes().then((result) => {
118
+ return result.device_makes.length;
119
+ }).catch((err) => {
120
+ /* ...handle the error... */
121
+ });
122
+ ```
123
+
124
+ #### Query Parameters
125
+
126
+ For query parameters, simply feed in an input that matches with the expected query parameters:
127
+ ```ts
128
+ dimo.devicedefinitions.getByMMY({
129
+ make: '<vehicle_make>',
130
+ model: '<vehicle_model',
131
+ year: 2021
132
+ });
133
+ ```
134
+ #### Path Parameters
135
+
136
+ For path parameters, simply feed in an input that matches with the expected path parameters:
137
+ ```ts
138
+ dimo.devicedefinitions.getById({ id: '26G4j1YDKZhFeCsn12MAlyU3Y2H' })
139
+ ```
140
+
141
+ #### Permission Tokens
142
+
143
+ As the 2nd leg of the API authentication, applications may exchange for short-lived [permissions JWT](https://docs.dimo.org/developer-platform/getting-started/developer-guide/authentication#getting-a-jwt) for specific vehicles that granted permissions to the app. This uses the [DIMO Token Exchange API](https://docs.dimo.org/developer-platform/api-references/dimo-protocol/token-exchange-api/token-exchange-api-endpoints).
144
+
145
+ For the end users of your application, they will need to share their vehicle permissions via the DIMO Mobile App or via your implementation of [Login with DIMO](https://docs.dimo.org/developer-platform/getting-started/developer-guide/login-with-dimo). Once vehicles are shared, you will be able to get a permissions JWT.
146
+
147
+ ```ts
148
+ const privToken = await dimo.tokenexchange.exchange({
149
+ ...auth,
150
+ privileges: [1, 5],
151
+ tokenId: <vehicle_token_id>
152
+ });
153
+
154
+ // Vehicle Status uses privId 1
155
+ await dimo.devicedata.getVehicleStatus({
156
+ ...privToken,
157
+ tokenId: <vehicle_token_id>
158
+ });
159
+
160
+ // Proof of Movement Verifiable Credentials uses privId 4
161
+ await dimo.attestation.createPomVC({
162
+ ...privToken,
163
+ tokenId: <vehicle_token_id>
164
+ })
165
+
166
+ // VIN Verifiable Credentials uses privId 5
167
+ await dimo.attestation.createVinVC({
168
+ ...privToken,
169
+ tokenId: <vehicle_token_id>
170
+ });
171
+ ```
172
+
173
+ ### Querying the DIMO GraphQL API
174
+
175
+ The SDK accepts any type of valid custom GraphQL queries, but we've also included a few sample queries to help you understand the DIMO GraphQL APIs.
176
+
177
+ #### Authentication for GraphQL API
178
+ The GraphQL entry points are designed almost identical to the REST API entry points. For any GraphQL API that requires auth headers (Telemetry API for example), you can use the same pattern as you would in the REST protected endpoints.
179
+
180
+ ```ts
181
+ const privToken = await dimo.tokenexchange.exchange({
182
+ ...auth,
183
+ privileges: [1, 3, 4],
184
+ tokenId: <vehicle_token_id>
185
+ });
186
+
187
+ const tele = await dimo.telemetry.query({
188
+ ...privToken,
189
+ query: `
190
+ query {
191
+ some_valid_GraphQL_query
192
+ }
193
+ `
194
+ });
195
+ ```
196
+
197
+ #### Send a custom GraphQL query
198
+ To send a custom GraphQL query, you can simply call the `query` function on any GraphQL API Endpoints and pass in any valid GraphQL query. To check whether your GraphQL query is valid, please visit our [Identity API GraphQL Playground](https://identity-api.dimo.zone/) or [Telemetry API GraphQL Playground](https://telemetry-api.dimo.zone/).
199
+
200
+ ```js
201
+ const yourQuery = `{
202
+ vehicles (first:10) {
203
+ totalCount
204
+ }
205
+ }`;
206
+
207
+ const totalNetworkVehicles = await dimo.identity.query({
208
+ query: yourQuery
209
+ });
210
+
211
+ ```
212
+
213
+ This GraphQL API query is equivalent to calling `dimo.identity.countDimoVehicles()`.
214
+
215
+ ## How to Contribute to the SDK
216
+ Read more about contributing [here](https://github.com/DIMO-Network/data-sdk/blob/master/CONTRIBUTING.md).
@@ -0,0 +1,2 @@
1
+ import { DimoEnvironment } from '../environments';
2
+ export declare const Method: (resource: any, baseUrl: any, params: any, env: keyof typeof DimoEnvironment) => Promise<any>;
@@ -0,0 +1,136 @@
1
+ import axios from 'axios';
2
+ import * as functionIndex from '../api/functions/';
3
+ import { DimoError } from '../errors';
4
+ export const Method = async (resource, baseUrl, params = {}, env) => {
5
+ /**
6
+ * Headers
7
+ */
8
+ let headers = {};
9
+ if (['access_token', 'privilege_token'].includes(resource.auth)) {
10
+ if (params.headers.Authorization) {
11
+ headers = params.headers;
12
+ }
13
+ else {
14
+ throw new DimoError({
15
+ message: `Access token not provided for ${resource.auth} authentication`,
16
+ statusCode: 401
17
+ });
18
+ }
19
+ }
20
+ if (resource.headers) {
21
+ headers = { ...headers, ...resource.headers };
22
+ }
23
+ // If resource.method is 'FUNCTION', call the function defined by 'resource.path'
24
+ if (resource.method === 'FUNCTION') {
25
+ const functionName = resource.path;
26
+ const dynamicFunction = functionIndex[functionName];
27
+ if (typeof dynamicFunction === 'function') {
28
+ // Call the dynamic function with params and pass the necessary arguments
29
+ return dynamicFunction(params, env);
30
+ }
31
+ else {
32
+ throw new DimoError({
33
+ message: `Function in ${resource.path} is not a valid function.`,
34
+ statusCode: 400
35
+ });
36
+ }
37
+ }
38
+ /**
39
+ * Query Parameters
40
+ * Extract required queryParams from the resource object
41
+ */
42
+ const queryParams = resource.queryParams || {};
43
+ // Check if required queryParams match with incoming params
44
+ for (const key in queryParams) {
45
+ // We'll fail early if there's a missing required query param from the user
46
+ if (queryParams[key] === true && !params[key]) {
47
+ console.error(`Missing required query parameter: ${key}`);
48
+ throw new DimoError({
49
+ message: `Missing required query parameter: ${key}`,
50
+ statusCode: 400
51
+ });
52
+ }
53
+ if (queryParams[key][0] === '$') {
54
+ const variableKey = queryParams[key].substring(1); // Remove the leading $
55
+ if (params[variableKey]) {
56
+ params[key] = params[variableKey]; // Set the value based on the value of the variable key
57
+ }
58
+ else {
59
+ console.error(`Variable key '${variableKey}' not found in params`);
60
+ throw new DimoError({
61
+ message: `Variable key '${variableKey}' not found in params`,
62
+ statusCode: 400
63
+ });
64
+ }
65
+ }
66
+ else if (typeof queryParams[key] === 'string') {
67
+ params[key] = queryParams[key];
68
+ }
69
+ }
70
+ /**
71
+ * URL Parameters
72
+ * Check for placeholders in the resource path and replace them with values from params
73
+ */
74
+ let url = baseUrl + resource.path;
75
+ const placeholderRegex = /:([\w]+)/g;
76
+ let match;
77
+ while ((match = placeholderRegex.exec(resource.path)) !== null) {
78
+ const key = match[1];
79
+ const value = params[key];
80
+ if (value !== undefined) {
81
+ url = url.replace(match[0], value.toString());
82
+ }
83
+ }
84
+ /**
85
+ * Body Parameters
86
+ */
87
+ let body = {};
88
+ if (resource.body) {
89
+ for (const key in resource.body) {
90
+ if (typeof resource.body[key] === 'boolean') {
91
+ if (!params[key]) {
92
+ console.error(`Missing required body parameter: ${key}`);
93
+ throw new DimoError({
94
+ message: `Missing required body parameter: ${key}`
95
+ });
96
+ }
97
+ else {
98
+ body[key] = params[key];
99
+ }
100
+ }
101
+ else if (typeof resource.body[key] === 'string') {
102
+ body[key] = resource.body[key];
103
+ }
104
+ }
105
+ }
106
+ try {
107
+ const response = await axios({
108
+ method: resource.method,
109
+ url: url,
110
+ params: resource.queryParams ? params : {},
111
+ data: resource.body ? body : '',
112
+ headers: headers
113
+ });
114
+ // Return response.data directly if resource.return does not exist
115
+ if (!resource.return) {
116
+ return response.data;
117
+ }
118
+ // Special returns for access_token & privilege token
119
+ let authHeader = {};
120
+ if (resource.return === 'access_token') {
121
+ authHeader = { Authorization: `Bearer ${response.data.access_token}` };
122
+ }
123
+ else if (resource.return === 'privilege_token') {
124
+ authHeader = { Authorization: `Bearer ${response.data.token}` };
125
+ }
126
+ return { headers: authHeader };
127
+ }
128
+ catch (error) {
129
+ console.error('API call error:', error.response.data);
130
+ throw new DimoError({
131
+ message: `API call error: ${error.response.data.message}`,
132
+ statusCode: error.response.data.code,
133
+ body: error.response.data
134
+ });
135
+ }
136
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,67 @@
1
+ import axios from 'axios';
2
+ import { Method } from './Method'; // Import the Method function to be tested
3
+ import { DimoError } from '../errors';
4
+ import { DimoEnvironment } from '../environments';
5
+ const PROD = 'Production';
6
+ const DEV = 'Dev';
7
+ const RESOURCE = {
8
+ method: 'GET',
9
+ path: '',
10
+ queryParams: { param1: true },
11
+ };
12
+ const PARAM = { param1: 'value1' };
13
+ describe('Method Function', () => {
14
+ test('Valid API Call - Device Definitions API Server is up and returning data', async () => {
15
+ jest.spyOn(axios, 'request').mockResolvedValue({ data: { key: 'value' } });
16
+ const devResponse = await Method(RESOURCE, DimoEnvironment.Dev.DeviceDefinitions, PARAM, DEV);
17
+ const prodResponse = await Method(RESOURCE, DimoEnvironment.Production.DeviceDefinitions, PARAM, PROD);
18
+ // Assertion - Check if the response data is returned correctly
19
+ expect(devResponse).toEqual('device definitions api running!');
20
+ expect(prodResponse).toEqual('device definitions api running!');
21
+ });
22
+ test('Valid API Call - Devices API Server is up and returning data', async () => {
23
+ jest.spyOn(axios, 'request').mockResolvedValue({ data: { key: 'value' } });
24
+ const devResponse = await Method(RESOURCE, DimoEnvironment.Dev.Devices, PARAM, DEV);
25
+ const prodResponse = await Method(RESOURCE, DimoEnvironment.Production.Devices, PARAM, PROD);
26
+ // Assertion - Check if the response data is returned correctly
27
+ expect(devResponse).toEqual({ data: 'Server is up and running' });
28
+ expect(prodResponse).toEqual({ data: 'Server is up and running' });
29
+ });
30
+ test('Valid API Call - Token Exchange API Server is up and returning data', async () => {
31
+ jest.spyOn(axios, 'request').mockResolvedValue({ data: { key: 'value' } });
32
+ const devResponse = await Method(RESOURCE, DimoEnvironment.Dev.TokenExchange, PARAM, DEV);
33
+ const prodResponse = await Method(RESOURCE, DimoEnvironment.Production.TokenExchange, PARAM, PROD);
34
+ // Assertion - Check if the response data is returned correctly
35
+ expect(devResponse).toEqual({ data: 'Server is up and running' });
36
+ expect(prodResponse).toEqual({ data: 'Server is up and running' });
37
+ });
38
+ test('Valid API Call - Valuations API Server is up and returning data', async () => {
39
+ jest.spyOn(axios, 'request').mockResolvedValue({ data: { key: 'value' } });
40
+ const devResponse = await Method(RESOURCE, DimoEnvironment.Dev.Valuations, PARAM, DEV);
41
+ const prodResponse = await Method(RESOURCE, DimoEnvironment.Production.Valuations, PARAM, PROD);
42
+ // Assertion - Check if the response data is returned correctly
43
+ expect(devResponse).toEqual({ code: 200, message: 'Server is up.' });
44
+ expect(prodResponse).toEqual({ code: 200, message: 'Server is up.' });
45
+ });
46
+ test('Valid API Call - Vehicle Signal Decoding API Server is up and returning data', async () => {
47
+ jest.spyOn(axios, 'request').mockResolvedValue({ data: { key: 'value' } });
48
+ const devResponse = await Method(RESOURCE, DimoEnvironment.Dev.VehicleSignalDecoding, PARAM, DEV);
49
+ const prodResponse = await Method(RESOURCE, DimoEnvironment.Production.VehicleSignalDecoding, PARAM, PROD);
50
+ // Assertion - Check if the response data is returned correctly
51
+ expect(devResponse).toEqual('healthy');
52
+ expect(prodResponse).toEqual('healthy');
53
+ });
54
+ test('Missing Required Query Parameter - Throws Error', async () => {
55
+ // Mock input data with missing required query parameter
56
+ const resource = {
57
+ method: 'GET',
58
+ path: '/example/endpoint',
59
+ queryParams: { expectedParam: true }, // Expect expectedParam
60
+ };
61
+ const baseUrl = 'https://example.com/api';
62
+ const params = { unexpectedParam: 'value1' };
63
+ // Call the Method function and expect it to throw an error
64
+ await expect(Method(resource, baseUrl, params, DEV)).rejects.toThrowError(DimoError);
65
+ await expect(Method(resource, baseUrl, params, PROD)).rejects.toThrowError(DimoError);
66
+ });
67
+ });