The notehub-js library is a JavaScript implementation for communicating with the Blues Notehub API generated by the OpenAPI Generator tool.
This library is auto-generated via the openapi.yaml file from the Blues Wireless Notehub project and published
to npm for ease of use in JavaScript-based projects that need to interact with Notehub.io.
- Blues Notehub JS
Using npm:
$ npm install @blues-inc/notehub-jsUsing yarn:
$ yarn add @blues-inc/notehub-jsOnce the package is installed, you can import the library using import or require:
import
import * as NotehubJs from "@blues-inc/notehub-js";
const defaultClient = NotehubJs.ApiClient.instance;NOTE: Using
importto access the library in a TypeScript project currently will cause an error because there is not yet a@typesfile for it. To make the error disappear, declare the module in a file with a.d.tsextension.declare module '@blues-inc/notehub-js';
require
const NotehubJs = require("@blues-inc/notehub-js");
const defaultClient = NotehubJs.ApiClient.instance;Here is an example of how to fetch all devices associated with a particular Notehub project.
The personalAccessToken variable declared below is a Personal Access Token (PAT) required for all Notehub API requests.
Creating a Personal Access Token
To create a PAT:
- Sign into Notehub
- Select "API Access" from the user menu
- Click "Create New Token"
- Name the token and set an expiration date
- Copy the generated token immediately (it won't be shown again)
Personal Access Tokens have the same permissions as your Notehub user account and should be stored securely like passwords. For more details, see the Notehub API documentation on Personal Access Tokens.
Once you have your PAT, supply it to the library by setting it equal to: personalAccessToken.accessToken = "YOUR_ACCESS_TOKEN"; in the code.
NOTE: Be aware that all Notehub API calls made using the Notehub JS library utilize your account's Consumption Credits (CCs). For > more information, please consult our pricing page.
import * as NotehubJs from "@blues-inc/notehub-js";
let defaultClient = NotehubJs.ApiClient.instance;
// Configure Bearer access token for authorization: personalAccessToken
let personalAccessToken = defaultClient.authentications["personalAccessToken"];
personalAccessToken.accessToken = "YOUR ACCESS TOKEN";
let apiInstance = new NotehubJs.ProjectApi();
let projectUID = "app:2606f411-dea6-44a0-9743-1130f57d77d8;"; // String |
let opts = {
pageSize: 50, // Number |
pageNum: 1, // Number |
};
// Want to use async/await? Add the 'async' keyword to your outer function/method.
apiInstance.getProjectDevices(projectUID, opts).then(
(data) => {
console.log(
"API called successfully. Returned data: " + JSON.stringify(data)
);
},
(error) => {
console.error(error);
}
);As this library gains adoptions, we'll continue to provide new links to repos where this library being used in real world projects.
Indoor Floor Level Tracker Project
If you'd like to see examples of this library being used in real-world applications, check out this indoor floor-level tracker project in the Blues App Accelerator repo on GitHub.
The files that deserve special attention are:
ServiceLocatorServer.ts- this file makes the variety of services composing the backend logic of the application discoverable to each other. For DRY-er code, the Notehub JS library's instances were created and passed to the various services that would require them to fetch and update data via the Notehub API. An instance of the Notehub JS client is created viaconst notehubJsClient = NotehubJs.ApiClient.instance, and passed to thegetDataProvider()andgetAttributeStore()services that will need to interact with the Notehub API to perform their duties.NotehubDataProvider.ts- this file is responsible for fetching data from the Notehub API for the application to display. It calls the project API'sgetProjectFleetDevices()andgetProjectEvents()methods, and the fleet API'sgetFleetEnvironmentVariables()method as well.NotehubAttributeStore.ts- this file sends updates to the Notehub API from the application like updated device name or updated environment variables. It calls two of the environment variable API's methods:putDeviceEnvironmentVariables()andputFleetEnvironmentVariables().
If you want more information, code examples of how to use each of the Notehub API endpoints are located in the src/docs/ folder and available on the Blues Developer Experience site.
Each API (device, event, fleet, etc.) had a .md file displaying:
- All the HTTP methods it supports,
- A full URL string of what the HTTP request looks like (including required and optional parameters),
- An example of how to implement the code for a particular method inside of a JavaScript application,
- A sample return type from a particular method,
- Required authorization to access the method.
As this project is partially generated via the OpenAPI Generator tool, it has a rather unique structure and some important files to be aware of.
.
├── .github/
│ └── scripts/
│ └── filter-deprecated-params.js
│ └── get-existing-beta-versions.sh
│ └── workflows/
│ └── publish-switch.yml
│ └── publish-prod-npm.yml
│ └── publish-beta-npm.yml
│ └── other GH Action files
├── .husky/
│ └── pre-commit files
├── libTemplate/
│ └── template files
├── src/
│ ├── src/
│ │ └── JS-based API and model files
│ ├── docs/
│ │ └── MD documentation
│ ├── test/
│ │ └── unit tests
│ ├── dist/
│ │ └── bundled src folder for npm
│ └── package.json
├── openapi.yaml
├── openapi.filtered.yaml
├── config.json
├── README.md
└── package.json
Files and folders to be aware of in the root of the project.
-
The
.github/folder holds the helper scripts and GitHub Actions workflows that automate common tasks in the repo. Key workflows include:publish-switch.yml- Single entry point for both production and beta npm publishing via trusted publishingpublish-prod-npm.yml- Production release workflow (called by publish-switch)publish-beta-npm.yml- Beta release workflow (called by publish-switch)
See the Deploying notehub-js to npm section for further information about the publishing architecture.
-
The
openapi.yamlis a key player for this project: it provides the documentation of all the Notehub API endpoints that the OpenAPI Generator tool uses to build the library - without this file, the project doesn't exist.
NOTE: Later, the
filter-deprecated-params.jsfile andopenapi.filtered.yamlfile were added to the SDK library. Thefilter-deprecated-params.jsfile makes a copy of theopenapi.yamlfile and removes any query params that have been marked asdeprecated. Eliminating these deprecated params makes the generated SDK docs and sample code easier to understand, and free from potentially confusing elements that could mislead users.
- The
libTemplate/folder is the JavaScript library template that the OpenAPI generator uses to generate thesrc/folder where auto-generated JS library is created.
NOTE: In many scenarios, downloading the OpenAPI Generator library template is not necessary, but there were some minor modifications needed in the template's generation to handle
nullandundefinedvalues in the same way that the original Notehub API handles them. Being able to download and modify those files offered the fine-grained control needed when generating the JS library code.If you ever need a fresh copy of the JS library template, run the following script command in the terminal to download it:
$ npm run downloadJsTemplate
-
The
config.jsonfile is a configuration file of additional properties used by the OpenAPI Generator and its JavaScript library template to define certain variables like license type, project name, project version, etc. -
The
.husky/folder is a set of pre-commit hooks that Husky runs on all files staged for commit to GitHub. It currently runs them through our Prettier file formatting tool via the pretty-quick npm library.
The src/ folder inside the root of the project contains the contents of the auto-generated notehub-js library that is eventually published to npm, including:
- The
docs/folder documenting how to access the API endpoints via the library, - The internal
src/folder that holds the JavaScript-basedapiandmodelfiles for each endpoint, - The
test/folder for unit tests, - And the
dist/folder contains the packaged up final version of the library shipped to npm.
NOTE: Do not modify the files in the
src/src/folder and thesrc/README.md- these are all auto-generated by the OpenAPI Generator tool and the next time the generator command is run to update the library any manual changes will be overwritten.
Instructions for how to modify or run this project locally.
This project uses Node.js as a runtime, npm as a package manager, and Volta as a way of enforcing consistent versions of all JavaScript-based tools. You can install these dependencies by completing the steps below.
- Install Volta by following its installation instructions.
- Run the command below in a terminal to install the appropriate versions of both Node.js and npm.
$ volta install node npm- Navigate to the root of the folder in your terminal or command prompt and run
npm install, which installs the repo's npm dependencies, including theprettier,pretty-quick, andhuskylibraries which will format any files staged for commit according to our coding style as defined in the.prettierrcfile.
$ npm installThe project also uses the OpenAPI Generator's CLI tool, so it's recommended to install that tool globally through the terminal.
$ npm install @openapitools/openapi-generator-cli -gNow you should be ready to make any changes or modifications.
Most of the files stored at the root of this project should require little to no modifications.
The lib/template folder holds the JavaScript generator template files the OpenAPI Generator tool relies upon to build its library in the src/ folder.
The .github/ folder holds helper scripts and GitHub Actions workflows that automate common tasks like creating PRs out of new branches, running automated tests, and publishing new releases to npm. The repository uses a single-entry-point workflow pattern (publish-switch.yml) for npm publishing, which calls separate reusable workflows for production and beta releases. All npm publishes use trusted publishing with OIDC for enhanced security.
The openapi.yaml file is a copy of the one in the Notehub repo (a private Blues repository). Anytime a new version of Notehub.io is deployed and the openapi.yaml file there is updated, a fresh copy of that file is added to this project in a new branch via a GitHub Actions workflow.
The filter-deprecated-params.js file, contained within the .github/scripts/ directory makes a copy of the openapi.yaml file called openapi.filtered.yaml which removes any query params marked as deprecated in the original openapi.yaml to prevent confusion for users about which query params are current vs deprecated. The openapi.filtered.yaml is what ends up being used to generate the Notehub JS SDK library.
The config.json file is the one that will require slight changes before a new version of the library is released to npm. The next section will elaborate further.
When the openapi.yaml file is updated in the original Notehub repo which this library supports, the updated file is copied over into a new feature branch in this repo through the magic of GitHub Actions.
When this occurs, it's time to regenerate the notehub-js JavaScript library based on the newly updated openapi.yaml.
To regenerate the notehub-js library:
- Git clone the repo from GitHub.
$ git clone [email protected]:blues/notehub-js.git- Check out the newly created remote branch from GitHub locally. (It will be named something like
feat-XYZ.) - Update the
config.jsonfile at the project's root so theprojectVersionparameter is incremented (please follow semantic versioning practices here). - At the root of the project, run the following script command from your terminal:
$ npm run filterOpenapiThis command will make a copy of the openapi.yaml file named openapi.filtered.yaml which has removed any query parameters marked as deprecated from the openapi.yaml file. Removing these now deprecated params ensures the generated SDK docs and sample code is clear,up-to-date, and free from potentially confusing artifacts to trip up users.
- Still at the root of the project, run the following script command from your terminal:
$ npm run generateDocsThis command will kick off the OpenAPI Generator tool to generate a new copy of the library inside of the src/ folder, which can then be merged to the main repo branch and released to npm.
NOTE: If you'd like more information about what exactly the
generateDocsscript is doing with its OpenAPI generator CLI commands, you can see the documentation for them here.
If you'd like to test some changes you've made to the notehub-js API locally before submitting a new PR to the repo, follow steps 1 - 4 above and then:
- Navigate into the
src/folder in the project and install and build the newly generated project.
- Install first.
$ npm install- Build next.
$ npm run build- Still inside the
src/folder, link it globally with npm.
$ npm link- Then go to the local JavaScript project where you want to use it, and add it as a local dependency in the project's
package.jsonfile with a relative path to the local library on your machine. The file path will probably look something like:
"dependencies": {
"../../notehub-js": "^1.0.5"
}- Install the module inside of your project.
npm install- Import the library using
importorrequireas documented above in your application code and test it out.
All of these directions are also available in the auto-generated README.md in the src/ folder as well, for reference.
NOTE: Even testing locally, you will need a Personal Access Token (this is the 'personalAccessToken' referenced in the code examples). See these directions on the Blues Developer Experience site to generate one.
Although many of the processes around this repository are automated with GitHub Actions, publishing an updated version of the repo requires some human intervention as well.
Below are the necessary steps to take a new version of the openapi.yaml file and make it ready to deploy to npm.
This repository uses npm trusted publishing with OIDC for secure, tokenless deployments. A single GitHub Actions workflow (publish-switch.yml) serves as the entry point for both production and beta releases:
- Production releases: Triggered when a new GitHub release is created
- Beta releases: Triggered when changes to
openapi.yamlare pushed to branches matchingtest-release-**
Both release types use npm's trusted publisher feature with provenance statements for supply chain security.
NOTE: The trusted publisher must be configured on npmjs.com to reference the
publish-switch.ymlworkflow file. This configuration allows both production and beta releases to authenticate via OIDC without requiring npm access tokens.
- Adjust the version number (
"projectVersion") in theconfig.jsonfile. (Failure to adjust"projectVersion"will cause the release to npm to fail; the same version number can't be published more than once.) - Run
npm run filterOpenapito create a fresh version of theopenapi.filtered.yamlfile that removes all deprecated query params from the originalopenapi.yamlfile. - Run
npm run generateDocsto generate new docs from theopenapi.filtered.yamlfile. - Commit and push the changes to a new branch in GitHub and open a new pull request when the branch is ready for review. See the contribution documentation for further details around a good PR and commit messages.
- Get the PR approved and merged to
main. - Create a new release with a tag following the semantic versioning style of [vX.X.X], click the "Generate release notes" button to log the changes in the release, and publish it. For example: a new release with a tag named v1.0.2.
- The
publish-switch.ymlGitHub Actions workflow will automatically detect the release event and trigger the production publish workflow, which will deploy the latest version of notehub-js to npm with provenance attestation.
During the course of the development cycle, it may make sense to have beta versions of a repo available on npm for testing purposes. These versions of the notehub-js repo are considered unstable and should not be used long term in production apps, they are meant for internal testing of new features before they're ready for public consumption. Here are the steps to deploy a beta version of the SDK to npm:
- Create a new feature branch with the name
test-release-BRANCH-NAME-OF-CHOICE, and modify theopenapi.yamlfile. Commit that new branch back to the Notehub JS repo. - Once committed, the
publish-switch.ymlGitHub Actions workflow will automatically detect the branch name pattern and trigger the beta publish workflow, which will:- Increment the project version with a
beta.XXtag - Regenerate the SDK with the new
openapi.yamlfile - Publish it as a beta version to npm with the
betatag and provenance attestation - Commit the updated project version back to the branch
- Increment the project version with a
Now, anyone can download the beta version of the Notehub JS with the following command:
npm install @blues-inc/[email protected]You can see all available project versions by visiting the Notehub JS npm page and clicking the "Versions" tab.
We love issues, fixes, and pull requests from everyone. By participating in this project, you agree to abide by the Blues Inc. code of conduct.
For details on contributions we accept and the process for contributing, see our contribution guide.
Copyright (c) 2023 Blues Inc. Released under the MIT license. See LICENSE for details.