{"id":22326026,"url":"https://github.com/solarnetwork/sn-api-core-js","last_synced_at":"2025-04-12T11:33:12.825Z","repository":{"id":22828482,"uuid":"97419675","full_name":"SolarNetwork/sn-api-core-js","owner":"SolarNetwork","description":"SolarNetwork Core API - JavaScript","archived":false,"fork":false,"pushed_at":"2025-04-03T00:18:05.000Z","size":6642,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-03T00:27:29.209Z","etag":null,"topics":["solarnetwork","typescript"],"latest_commit_sha":null,"homepage":"https://solarnetwork.github.io/sn-api-core-js/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/SolarNetwork.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-17T00:25:29.000Z","updated_at":"2025-02-13T04:27:20.000Z","dependencies_parsed_at":"2023-10-14T16:52:39.778Z","dependency_job_id":"2b39775f-7c74-4791-884e-73e73e673e34","html_url":"https://github.com/SolarNetwork/sn-api-core-js","commit_stats":{"total_commits":308,"total_committers":4,"mean_commits":77.0,"dds":"0.022727272727272707","last_synced_commit":"737c71da76de9194a91a65323d6160141e5c6938"},"previous_names":[],"tags_count":55,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SolarNetwork%2Fsn-api-core-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SolarNetwork%2Fsn-api-core-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SolarNetwork%2Fsn-api-core-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/SolarNetwork%2Fsn-api-core-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/SolarNetwork","download_url":"https://codeload.github.com/SolarNetwork/sn-api-core-js/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248560367,"owners_count":21124638,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["solarnetwork","typescript"],"created_at":"2024-12-04T02:15:05.727Z","updated_at":"2025-04-12T11:33:12.819Z","avatar_url":"https://github.com/SolarNetwork.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SolarNetwork Core API - JavaScript\n\nThis project contains JavaScript code to help access the [SolarNetwork API][solarnet-api].\nTo include the library in your NPM-based project, run the following:\n\n```sh\nnpm i solarnetwork-api-core\n```\n\n# API docs\n\nThe latest API documentation is published [here](https://solarnetwork.github.io/sn-api-core-js/), or\nyou can build the API documentation by running the `apidoc` script:\n\n```sh\nnpm run apidoc\n```\n\nThat will produce HTML documentation in `docs/html`.\n\n# Example: Query datum\n\nHere's an example use of the library, targeted for use in a browser using the [Fetch API][fetch] to\naccess the [/datum/stream/reading][stream-reading] SolarNetwork API:\n\n```ts\nimport {\n\tAggregations,\n\tDatum,\n\tDatumFilter,\n\tDatumReadingTypes,\n\tDatumStreamMetadataInfo,\n\tResult,\n} from \"solarnetwork-api-core/domain\";\nimport {\n\tAuthorizationV2Builder,\n\tHttpContentType,\n\tHttpHeaders,\n\tHttpMethod,\n\tSolarQueryApi,\n} from \"solarnetwork-api-core/net\";\nimport {\n\tDatumStreamMetadataRegistry,\n\tDatum as DatumUtil,\n} from \"solarnetwork-api-core/util\";\n\n/**\n * Fetch hourly reading data for a datum stream using the stream API.\n *\n * @param nodeId - the node ID to fetch data for\n * @param sourceId  - the source ID to fetch data for\n * @param startDate - the minimum date\n * @param endDate - the maximum date\n * @param token - the security token to authenticate with\n * @param tokenSecret - the security token secret\n * @returns the data, as an array of general datum\n */\nasync function fetchReadingDatumStream(\n\tnodeId: number,\n\tsourceId: string,\n\tstartDate: Date,\n\tendDate: Date,\n\ttoken: string,\n\ttokenSecret: string\n): Promise\u003cDatum[]\u003e {\n\tconst filter = new DatumFilter();\n\tfilter.aggregation = Aggregations.Hour;\n\tfilter.nodeId = nodeId;\n\tfilter.sourceId = sourceId;\n\tfilter.startDate = startDate;\n\tfilter.endDate = endDate;\n\n\t// encode the URL request for the /datum/stream/reading API\n\tconst urlHelper = new SolarQueryApi();\n\tconst streamDataUrl = urlHelper.streamReadingUrl(\n\t\tDatumReadingTypes.Difference,\n\t\tfilter\n\t);\n\n\t// create URL and auth headers for API request\n\tconst auth = new AuthorizationV2Builder(token);\n\tconst authHeader = auth.snDate(true).url(streamDataUrl).build(tokenSecret);\n\tconst headers = new Headers({\n\t\tAuthorization: authHeader,\n\t\tAccept: HttpContentType.APPLICATION_JSON,\n\t});\n\theaders.set(HttpHeaders.X_SN_DATE, auth.requestDateHeaderValue!);\n\n\t// make API request and get response as JSON\n\tconst res = await fetch(streamDataUrl, {\n\t\tmethod: HttpMethod.GET,\n\t\theaders: headers,\n\t});\n\tconst json = (await res.json()) as Result\u003cany\u003e;\n\n\t// convert stream result into Datum objects\n\tconst result: Datum[] = [];\n\tconst meta: DatumStreamMetadataInfo[] = json.meta!;\n\tconst reg = DatumStreamMetadataRegistry.fromJsonObject(meta);\n\tif (!reg) {\n\t\treturn Promise.reject(\"JSON could not be parsed.\");\n\t}\n\tfor (const data of json.data) {\n\t\tconst meta = reg.metadataAt(data[0]);\n\t\tif (!meta) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst d = DatumUtil.datumForStreamData(data, meta)?.toObject();\n\t\tif (d) {\n\t\t\tresult.push(new Datum(d.toObject()));\n\t\t}\n\t}\n\treturn Promise.resolve(result);\n}\n```\n\n# Example: DatumLoader\n\nThe `DatumLoader` class helps return data from the SolarQuery [/datum/list][api-datum-list]\nendpoint. The class takes care of loading all results for a given search criteria, including making\nmultiple API requests to download all result pages when more than one page of results are available.\n\nHere's an example of loading a month's worth of data for SolarNode 123:\n\n```js\nconst filter = new DatumFilter();\nfilter.nodeId = 123;\nfilter.startDate = new Date(\"Sat, 1 Apr 2017 12:00:00 GMT\");\nfilter.endDate = new Date(\"Mon, 1 May 2017 12:00:00 GMT\");\n\nconst api = new SolarQueryApi();\n\nnew DatumLoader(api, filter).load((error, results) =\u003e {\n\t// results is an array of Datum objects\n});\n```\n\nA Promise based API is available as well:\n\n```js\nconst result = await new DatumLoader(api, filter).fetch();\n```\n\n# Example: MultiLoader\n\nThe `MultiLoader` class helps load data from multiple `Loader` objects (the\n`DatumLoader` class conforms to that interface). This is useful for pulling\ndown data from different search criterias all in one go. For example:\n\n```js\nconst filter1 = new DatumFilter();\nfilter1.nodeId = 123;\nfilter1.sourceId = \"a\";\n\nconst filter2 = new DatumFilter();\nfilter2.nodeId = 234;\nfilter2.sourceIds = [\"b\", \"c\"];\n\nconst api = new SolarQueryApi();\n\nnew MultiLoader([\n\tnew DatumLoader(api, filter1),\n\tnew DatumLoader(api, filter2),\n]).load((error, results) =\u003e {\n\t// results is a 2-element array of Datum arrays\n});\n\n# or via promise...\nconst result = await new MultiLoader([\n\tnew DatumLoader(api, filter1),\n\tnew DatumLoader(api, filter2),\n]).fetch();\n```\n\n# Example: DatumRangeFinder\n\nThe `DatumRangeFinder` class helps find the date range of available data for a set of SolarNodes.\nThis is useful when generating reports or charts for a set of SolarNode datum streams, so the\noverall start/end dates can be determined before requesting the actual data. For example:\n\n```js\nconst api = new SolarQueryApi();\n\nconst filter = new DatumFilter();\nfilter.nodeId = 123;\nfilter.sourceIds = [\"a\", \"b\"];\n\nconst range = await new DatumRangeFinder(api, filter).fetch();\n```\n\nRanges for more complex queries can be accomplished by passing in an array of filters, like this\nexample, continuing from the last one:\n\n```js\nconst filter2 = new DatumFilter();\nfilter2.nodeId = 234;\nfilter2.sourceId = \"c\";\n\nconst range2 = await new DatumRangeFinder(api, [filter1, filter2]).fetch();\n```\n\n# Example: DatumSourceFinder\n\nThe `DatumSourceFinder` class helps find the available source IDs for a set of node IDs.\n\n```js\nconst api = new SolarQueryApi();\n\nconst filter = new DatumFilter();\nfilter.nodeId = 123;\n\nconst sources = await new DatumSourceFinder(api, filter).fetch();\n```\n\nWildcard patterns can also be used to limit the search to a more specific set of source IDs,\nand start/end dates can also be used to narrow the search, for example:\n\n```js\nconst api = new SolarQueryApi();\n\nconst filter = new DatumFilter();\nfilter.startDate = new Date(Date.now() - 24 * 60 * 60 * 1000);\nfilter.sourceId = \"/power/**\";\n\nconst sources2 = await new DatumSourceFinder(api, filter).fetch();\n```\n\n# Example: Control Toggler\n\nControl Toggler is a helper class that uses the SolarNetwork [Instruction API][api-queue-instr] to\nrequest a SolarNode to set the value of a _control_ to `1` (on) or `0` (off), and the\nSolarNetwork [Datum Query API][api-datum-recent] to track the value of the control.\n\nThe Instruction API is asynchronous and changing a control value requires the following steps:\n\n-   Enqueue instruction to set control value\n-   Wait for SolarNode to receive, execute, and update instruction status to `Completed` (or `Rejected`)\n-   Wait for SolarNode to post updated control value datum for confirmation\n\nControl Toggler handles these steps through a simple API for setting the desired value and using\na callback function to get notified when the value changes.\n\nSome example SolarNode plugins that support on/off switching are:\n\n-   [Mock Control](https://github.com/SolarNetwork/solarnetwork-node/tree/master/net.solarnetwork.node.control.mock) (good for testing)\n-   [LATA switch](https://github.com/SolarNetwork/solarnetwork-node/tree/master/net.solarnetwork.node.control.jf2.lata)\n-   [Modbus switch](https://github.com/SolarNetwork/solarnetwork-node/tree/master/net.solarnetwork.node.control.modbus.toggle)\n\n# Upgrading from 1.x\n\nThe 2.x version of this library has changed somewhat as the 1.x library was ported\nto TypeScript and updated to ES2022. Most of the same classes and methods have\nbeen preserved, but some things have moved namespaces. Thankfully the move to\nTypeScript makes refactoring an application using the 1.x API pretty straightforward,\nas your IDE can usually offer the correct `import` path to use for a given class.\n\nFor example, in the 1.x API you might have:\n\n```js\nimport {\n\tAggregations,\n\tAuthorizationV2Builder,\n\tDatumFilter,\n\tDatumReadingTypes,\n\tDatumStreamMetadataRegistry,\n\tNodeDatumUrlHelper,\n\tstreamDatumUtils,\n} from \"solarnetwork-api-core\";\n```\n\nMost of those exist in the 2.x API, just under different import paths:\n\n```ts\nimport {\n\tAggregations,\n\tDatumFilter,\n\tDatumReadingTypes,\n} from \"solarnetwork-api-core/domain\";\nimport {\n\tAuthorizationV2Builder,\n\tSolarQueryApi, // \u003c-- this replaces the NodeDatumUrlHelper!\n} from \"solarnetwork-api-core/net\";\nimport { DatumStreamMetadataRegistry } from \"solarnetwork-api-core/util\";\nimport { datumForStreamData } from \"solarnetwork-api-core/util/datum\";\n```\n\nOne area that has changed somewhat significantly is the `net` namespace. The\nvarious `*UrlHelper` classes have been reworked into `Solar*Api` classes, such\nas `SolarQueryApi` and `SolarUserApi`. The methods offered on those classes\nremain mostly the same as in the 1.x library, but be sure to confirm with\nthe API docs. Here again your IDE will generally be able to point out broken\nAPI usage, thanks to the TypeScript definitions included in the library.\n\n# Building\n\nThe build uses [NPM][npm] and requires Node 20+. First, initialize the dependencies:\n\n```sh\nnpm ci\n```\n\nThen you can run the `build` script:\n\n```sh\nnpm run build:dist\n```\n\nThat will produce ES2022 modules with an entry point in `lib/index.js`.\n\nYou can also produce an ES2022 bundle by running `npm run build:bundle`. That will produce a single\nbundled file at `lib/solarnetwork-api-core.es.js`.\n\nYou can also produce an CJS bundle by running `npm run build:bundle:cjs`. That will produce a single\nbundled file at `lib/solarnetwork-api-core.es.cjs`. This bundle embeds 3rd party dependencies as well.\n\n# Releases\n\nReleases are done using the gitflow branching model. Gitflow must be installed on your host system.\nThen you can run\n\n```shell\nnpm run release\n```\n\nto version, build, commit, and publish the release. See the [generate-release][generate-release]\nsite for more information.\n\n# Unit tests\n\nThe unit tests can be run by running the `test` script:\n\n```sh\nnpm test\n```\n\nThat will output the test results and produce a HTML code coverage report at `coverage/index.html`.\n\n[![codecov](https://codecov.io/gh/SolarNetwork/sn-api-core-js/graph/badge.svg?token=2YA6X8LUX7)](https://codecov.io/gh/SolarNetwork/sn-api-core-js)\n\nHaving a well-tested and reliable library is a core goal of this project. Unit tests are executed\nautomatically after every push into the `develop` branch of this repository and their associated code\ncoverage is uploaded to [Codecov](https://codecov.io/github/SolarNetwork/sn-api-core-js/).\n\n[![codecov](https://codecov.io/gh/SolarNetwork/sn-api-core-js/graphs/sunburst.svg?token=2YA6X8LUX7)](https://codecov.io/github/SolarNetwork/sn-api-core-js)\n\n[api-queue-instr]: https://github.com/SolarNetwork/solarnetwork/wiki/SolarUser-API#queue-instruction\n[api-datum-list]: https://github.com/SolarNetwork/solarnetwork/wiki/SolarQuery-API#datum-list\n[api-datum-recent]: https://github.com/SolarNetwork/solarnetwork/wiki/SolarQuery-API#most-recent-datum\n[fetch]: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n[generate-release]: https://github.com/mrkmg/node-generate-release\n[npm]: https://www.npmjs.com/\n[solarnet-api]: https://github.com/SolarNetwork/solarnetwork/wiki/API-Developer-Guide\n[stream-reading]: https://github.com/SolarNetwork/solarnetwork/wiki/SolarQuery-Stream-API#datum-stream-reading-list\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsolarnetwork%2Fsn-api-core-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsolarnetwork%2Fsn-api-core-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsolarnetwork%2Fsn-api-core-js/lists"}