Code Monkey home page Code Monkey logo

sn-api-core-js's Introduction

SolarNetwork Core API - JavaScript

This project contains JavaScript code to help access the SolarNetwork API. To include the library in your NPM-based project, run the following:

npm i solarnetwork-api-core

API docs

The latest API documentation is published here, or you can build the API documentation by running the apidoc script:

npm run apidoc

That will produce HTML documentation in docs/html.

Example

Here's an example use of the library, targeted for use in a browser using the Fetch API to access the /datum/stream/reading SolarNetwork API:

import {
	Aggregations,
	DatumFilter,
	DatumReadingTypes,
} from "solarnetwork-api-core/lib/domain";
import {
	AuthorizationV2Builder,
	HttpContentType,
	HttpHeaders,
	HttpMethod,
	SolarQueryApi,
} from "solarnetwork-api-core/lib/net";
import { DatumStreamMetadataRegistry } from "solarnetwork-api-core/lib/util";
import { datumForStreamData } from "solarnetwork-api-core/lib/util/datum";

// declare a basic "datum" interface for the data returned from SN
interface GeneralDatum extends Object {
	nodeId: number;
	sourceId: string;
	date: Date;
	[index: string]: any;
}

/**
 * Fetch hourly reading data for a datum stream using the stream API.
 *
 * @param nodeId - the node ID to fetch data for
 * @param sourceId  - the source ID to fetch data for
 * @param startDate - the minimum date
 * @param endDate - the maximum date
 * @param token - the security token to authenticate with
 * @param tokenSecret - the security token secret
 * @returns the data, as an array of general datum
 */
async function fetchReadingDatumStream(
	nodeId: number,
	sourceId: string,
	startDate: Date,
	endDate: Date,
	token: string,
	tokenSecret: string
): Promise<GeneralDatum[]> {
	const filter = new DatumFilter();
	filter.aggregation = Aggregations.Hour;
	filter.nodeId = nodeId;
	filter.sourceId = sourceId;
	filter.startDate = startDate;
	filter.endDate = endDate;

	// encode the URL request for the /datum/stream/reading API
	const urlHelper = new SolarQueryApi();
	const streamDataUrl = urlHelper.streamReadingUrl(
		DatumReadingTypes.Difference,
		filter
	);

	// create URL and auth headers for API request
	const auth = new AuthorizationV2Builder(token);
	const authHeader = auth.snDate(true).url(streamDataUrl).build(tokenSecret);
	const headers = new Headers({
		Authorization: authHeader,
		Accept: HttpContentType.APPLICATION_JSON,
	});
	headers.set(HttpHeaders.X_SN_DATE, auth.requestDateHeaderValue!);

	// make API request and get response as JSON
	const res = await fetch(streamDataUrl, {
		method: HttpMethod.GET,
		headers: headers,
	});
	const json = await res.json();

	// convert stream result into GeneralDatum objects
	const result: GeneralDatum[] = [];
	const reg = DatumStreamMetadataRegistry.fromJsonObject(json.meta);
	if (!reg) {
		return Promise.reject("JSON could not be parsed.");
	}
	for (const data of json.data) {
		const meta = reg.metadataAt(data[0]);
		if (!meta) {
			continue;
		}
		const d = datumForStreamData(data, meta)?.toObject();
		if (d) {
			result.push(d as GeneralDatum);
		}
	}
	return Promise.resolve(result);
}

Upgrading from 1.x

The 2.x version of this library has changed somewhat as the 1.x library was ported to TypeScript and updated to ES2022. Most of the same classes and methods have been preserved, but some things have moved namespaces. Thankfully the move to TypeScript makes refactoring an application using the 1.x API pretty straightforward, as your IDE can usually offer the correct import path to use for a given class.

For example, in the 1.x API you might have:

import {
	Aggregations,
	AuthorizationV2Builder,
	DatumFilter,
	DatumReadingTypes,
	DatumStreamMetadataRegistry,
	NodeDatumUrlHelper,
	streamDatumUtils,
} from "solarnetwork-api-core";

Most of those exist in the 2.x API, just under different import paths:

import {
	Aggregations,
	DatumFilter,
	DatumReadingTypes,
} from "solarnetwork-api-core/lib/domain";
import {
	AuthorizationV2Builder,
	SolarQueryApi, // <-- this replaces the NodeDatumUrlHelper!
} from "solarnetwork-api-core/lib/net";
import { DatumStreamMetadataRegistry } from "solarnetwork-api-core/lib/util";
import { datumForStreamData } from "solarnetwork-api-core/lib/util/datum";

One area that has changed somewhat significantly is the net namespace. The various *UrlHelper classes have been reworked into Solar*Api classes, such as SolarQueryApi and SolarUserApi. The methods offered on those classes remain mostly the same as in the 1.x library, but be sure to confirm with the API docs. Here again your IDE will generally be able to point out broken API usage, thanks to the TypeScript definitions included in the library.

Building

The build uses NPM and requires Node 17+. First, initialize the dependencies:

npm ci

Then you can run the build script:

npm run build:dist

That will produce ES2022 modules with an entry point in lib/index.js.

You can also produce an ES2022 bundle by running npm run build:bundle. That will produce a single bundled file at lib/solarnetwork-api-core.es.js.

Releases

Releases are done using the gitflow branching model. Gitflow must be installed on your host system. Then you can run

npm run release

to version, build, commit, and publish the release. See the generate-release site for more information.

Unit tests

The unit tests can be run by running the test script:

npm test

That will output the test results and produce a HTML code coverage report at coverage/index.html.

codecov

Having a well-tested and reliable library is a core goal of this project. Unit tests are executed automatically after every push into the develop branch of this repository and their associated code coverage is uploaded to Codecov.

codecov

sn-api-core-js's People

Contributors

brettanomyces avatar dependabot[bot] avatar msqr avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

brettanomyces

sn-api-core-js's Issues

Error: Could not resolve '../util/PropMap' from src/domain/location.js

npm run build fails with the following message:

Error: Could not resolve '../util/PropMap' from src/domain/location.js

Cause is incorrect capitalization of propMap.

Fix:


diff --git a/src/domain/location.js b/src/domain/location.js
index 8e084e1..a1b97f2 100644
--- a/src/domain/location.js
+++ b/src/domain/location.js
@@ -1,4 +1,4 @@
-import PropMap from '../util/PropMap';
+import PropMap from '../util/propMap';
 
 const CountryKey = 'country';
 const ElevationKey = 'elevation';

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.