Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ exports return `Uint8Array`. The server handles calendar boundaries and rounding
| `meterReadings` | `list`, `create`, `delete`, `export` |
| `environments` | `list`, `get`, `create`, `delete`, `createEntry`, `deleteEntry` |
| `calculations` | `dailyValues`, `extrapolations` |
| `token` | `status` |

See [API usage](https://github.com/energy-tracker/api-client-typescript/blob/main/docs/api.md) for options and errors.

Expand Down
12 changes: 8 additions & 4 deletions contracts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,17 @@ test and release checks. No API token, live backend or sibling checkout is neede
present, `retryAfter` in seconds. Exception class names and local wording are
language-specific. Assert exactly one request, including on errors/redirects.

Compare `timestamp`, `date`, `lastUpdatedAt`, `from`, `to`, `updatedAfter` and
`updatedBefore` as offset-aware instants. `Z` and equivalent offsets/fractional
spellings are interchangeable. Do not round to calendar boundaries. Compare
all other values directly, preserving decimal precision and list order.
Compare `timestamp`, `date`, `lastUpdatedAt`, `expiresAt`, `from`, `to`,
`updatedAfter` and `updatedBefore` as offset-aware instants. `Z` and equivalent
offsets/fractional spellings are interchangeable. Do not round to calendar
boundaries. Compare all other values directly, preserving decimal precision and
list order. Token scopes compare as strings; scopes unknown to an SDK pass
through unchanged.

The wire examples were checked against the Public API controllers and DTOs in
[energy-tracker-core at fcc269a06184426caf64c882291d4209be57a723](https://github.com/StefaniOSApps/energy-tracker-core/tree/fcc269a06184426caf64c882291d4209be57a723/backend/src/app/public-api).
The token status examples were checked against
[energy-tracker-core at 969b1b722d3e56505c86ecdd098e1bcebaff90b3](https://github.com/StefaniOSApps/energy-tracker-core/tree/969b1b722d3e56505c86ecdd098e1bcebaff90b3/backend/src/app/public-api).
Error/redirect/malformed-response cases additionally specify SDK behavior; their
messages are illustrative, not fixed backend wording. These mocked responses
do not verify server calculations, validation rules or authorization scopes.
Expand Down
37 changes: 37 additions & 0 deletions contracts/cases/errors.json
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,43 @@
}
}
},
{
"id": "token-status-wrong-status",
"operation": "token.status",
"input": {},
"request": {
"method": "GET",
"path": "/v1/token/status",
"query": {},
"headers": {
"Authorization": "Bearer contract-test-token"
},
"body": {}
},
"response": {
"status": 201,
"headers": {
"Content-Type": "application/json"
},
"body": {
"json": {
"displayName": "Home Assistant Zählerschrank",
"scopes": [
"write:meter-reading",
"read:measuring-device"
],
"expiresAt": "2027-01-01T00:00:00.000Z"
}
}
},
"expected": {
"error": {
"kind": "api",
"status": 201,
"messages": []
}
}
},
{
"id": "readings-create-error-400",
"operation": "meterReadings.create",
Expand Down
123 changes: 123 additions & 0 deletions contracts/cases/token.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
{
"schemaVersion": 1,
"cases": [
{
"id": "token-status",
"operation": "token.status",
"input": {},
"request": {
"method": "GET",
"path": "/v1/token/status",
"query": {},
"headers": {
"Authorization": "Bearer contract-test-token"
},
"body": {}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"json": {
"displayName": "Home Assistant Zählerschrank",
"scopes": [
"write:meter-reading",
"read:measuring-device"
],
"expiresAt": "2027-01-01T00:00:00.000Z"
}
}
},
"expected": {
"result": {
"displayName": "Home Assistant Zählerschrank",
"scopes": [
"write:meter-reading",
"read:measuring-device"
],
"expiresAt": "2027-01-01T00:00:00.000Z"
}
}
},
{
"id": "token-status-no-expiry",
"operation": "token.status",
"input": {},
"request": {
"method": "GET",
"path": "/v1/token/status",
"query": {},
"headers": {
"Authorization": "Bearer contract-test-token"
},
"body": {}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"json": {
"displayName": "Write only",
"scopes": [
"write:meter-reading"
],
"expiresAt": null
}
}
},
"expected": {
"result": {
"displayName": "Write only",
"scopes": [
"write:meter-reading"
],
"expiresAt": null
}
}
},
{
"id": "token-status-unknown-scope",
"operation": "token.status",
"input": {},
"request": {
"method": "GET",
"path": "/v1/token/status",
"query": {},
"headers": {
"Authorization": "Bearer contract-test-token"
},
"body": {}
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body": {
"json": {
"displayName": "Newer backend",
"scopes": [
"meter-reading",
"read:future-resource"
],
"expiresAt": null
}
}
},
"expected": {
"result": {
"displayName": "Newer backend",
"scopes": [
"meter-reading",
"read:future-resource"
],
"expiresAt": null
}
}
}
]
}
22 changes: 21 additions & 1 deletion contracts/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"environments.createEntry",
"environments.deleteEntry",
"calculations.dailyValues",
"calculations.extrapolations"
"calculations.extrapolations",
"token.status"
]
},
"input": {
Expand Down Expand Up @@ -714,6 +715,25 @@
}
}
}
},
{
"if": {
"properties": {
"operation": {
"const": "token.status"
}
}
},
"then": {
"properties": {
"input": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
}
}
}
}
]
},
Expand Down
9 changes: 5 additions & 4 deletions contracts/source.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"repository": "https://github.com/energy-tracker/api-client-python",
"commit": "6cf17f0631e3f71038da3ac06ce91e82965e1cf2",
"commit": "365416bfb5e559d548d94f0c0d5dae22c11c3504",
"sha256": {
"README.md": "985242aa12e06502b0dcbdf75ec3b95c8fd840dee4a1f309620f1b338e64a59a",
"README.md": "e2431d82e993a3529e81651303e3c0c741c65a93c8aa59673dc08fcf2bdb9e17",
"cases/calculations.json": "0065dc017f173c15b21dbc3b40c3e37d1f1ea80b957669ad50df20f9e888efe0",
"cases/devices.json": "7324964ac126b43b1d6070cf685ddae4e5659f6edbc8c934af34a796453bf15b",
"cases/environments.json": "c069c180405e1414029fe496e46f0272242e6f4d421b1754f16e442307f5cdd8",
"cases/errors.json": "5bdeeaa2bdfe5b042ef2fa15bc53d06b422547a9a5535c85cc82c09b382fe721",
"cases/errors.json": "aaf5d43da99ac791976bce6ddd3b3b70d0b4c10ab808b802d1589c5f474776a6",
"cases/meter-readings.json": "f6ab1fd908cdabc69c2238c8c91188e5e862186716cb4bdc63f7f4195ffd115c",
"schema.json": "e91982f7d62a1bae6d48f5c1614fcf1cda9f3e27c32249aee602c2cfa5c9dc2d"
"cases/token.json": "be9df153140912a745a48dbf101208b5c6f913781de340905f4980995809a2d8",
"schema.json": "fe20b470fc5103bc84e8b2f45931fcc1904b3110a7d9e972c91fe5e71b2b5234"
}
}
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@energy-tracker/api-client",
"version": "2.0.0",
"version": "2.1.0",
"description": "Typed async client for the Energy Tracker public API",
"license": "MIT",
"author": "Stefan Nebel",
Expand Down
3 changes: 2 additions & 1 deletion scripts/check-package.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ try {
const esm = `import { EnergyTrackerClient, ValidationError } from '${pkg.name}'; import { createRequire } from 'node:module'; const cjs = createRequire(import.meta.url)('${pkg.name}'); if (EnergyTrackerClient !== cjs.EnergyTrackerClient || ValidationError !== cjs.ValidationError) throw Error('Module identity mismatch');`;
await writeFile(join(temp, 'smoke.mjs'), esm);
execFileSync(process.execPath, [join(temp, 'smoke.mjs')], { cwd: temp, stdio: 'inherit' });
const consumer = `import { EnergyTrackerClient, CalculationInterval, type MeterReadingDto } from '${pkg.name}';
const consumer = `import { EnergyTrackerClient, CalculationInterval, TokenScope, type MeterReadingDto } from '${pkg.name}';
const client = new EnergyTrackerClient({accessToken: 'test'});
const result: Promise<MeterReadingDto[]> = client.meterReadings.list('device');
void result;
void client.meterReadings.create('device', {value: '9999999999.999999', timestamp: new Date()});
void client.calculations.extrapolations('device', {interval: CalculationInterval.MONTH});
void client.token.status().then((status) => status.scopes.includes(TokenScope.WRITE_METER_READING) || status.scopes.includes('read:future-resource'));
// @ts-expect-error Meter values must not lose precision through a number.
void client.meterReadings.create('device', {value: 123.45});
// @ts-expect-error Unsupported intervals must be rejected by the type system.
Expand Down
3 changes: 3 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CalculationResource } from './resources/calculations.js';
import { DeviceResource } from './resources/devices.js';
import { EnvironmentResource } from './resources/environments.js';
import { MeterReadingResource } from './resources/meter-readings.js';
import { TokenResource } from './resources/token.js';
import { Transport } from './transport.js';
import type { ClientOptions } from './transport.js';

Expand All @@ -10,12 +11,14 @@ export class EnergyTrackerClient {
readonly meterReadings: MeterReadingResource;
readonly environments: EnvironmentResource;
readonly calculations: CalculationResource;
readonly token: TokenResource;

constructor(options: ClientOptions) {
const transport = new Transport(options);
this.devices = new DeviceResource(transport);
this.meterReadings = new MeterReadingResource(transport);
this.environments = new EnvironmentResource(transport);
this.calculations = new CalculationResource(transport);
this.token = new TokenResource(transport);
}
}
9 changes: 9 additions & 0 deletions src/decoders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type {
DeviceSummaryDto,
EnvironmentRecordDto,
MeterReadingDto,
TokenStatusDto,
} from './models.js';

function object(value: unknown): Record<string, unknown> {
Expand Down Expand Up @@ -85,3 +86,11 @@ export function calculation(value: unknown): CalculationPointDto {
expectedDuration: number(data.expectedDuration, true),
};
}
export function tokenStatus(value: unknown): TokenStatusDto {
const data = object(value);
return {
displayName: string(data.displayName),
scopes: list(string)(data.scopes),
expiresAt: data.expiresAt == null ? null : date(data.expiresAt),
};
}
23 changes: 23 additions & 0 deletions src/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,23 @@ export const CalculationInterval = {
export type CalculationInterval = (typeof CalculationInterval)[keyof typeof CalculationInterval];
export const ExtrapolationMethod = { STANDARD: 'standard' } as const;
export type ExtrapolationMethod = (typeof ExtrapolationMethod)[keyof typeof ExtrapolationMethod];
export const TokenScope = {
READ_DAILY_VALUES: 'read:daily-values',
READ_EXTRAPOLATION: 'read:extrapolation',
METER_READING: 'meter-reading',
READ_METER_READING: 'read:meter-reading',
WRITE_METER_READING: 'write:meter-reading',
DELETE_METER_READING: 'delete:meter-reading',
MEASURING_DEVICE: 'measuring-device',
READ_MEASURING_DEVICE: 'read:measuring-device',
WRITE_MEASURING_DEVICE: 'write:measuring-device',
DELETE_MEASURING_DEVICE: 'delete:measuring-device',
ENVIRONMENT_RECORD: 'environment-record',
READ_ENVIRONMENT_RECORD: 'read:environment-record',
WRITE_ENVIRONMENT_RECORD: 'write:environment-record',
DELETE_ENVIRONMENT_RECORD: 'delete:environment-record',
} as const;
export type TokenScope = (typeof TokenScope)[keyof typeof TokenScope];

export interface DeviceSummaryDto {
readonly id: string;
Expand Down Expand Up @@ -86,6 +103,12 @@ export interface CalculationPointDto {
readonly expectedValue: number;
readonly expectedDuration: number;
}
export interface TokenStatusDto {
readonly displayName: string;
/** A scope added by a newer API is kept as a plain string. */
readonly scopes: readonly (TokenScope | (string & {}))[];
readonly expiresAt: Date | null;
}

export interface RequestOptions {
signal?: AbortSignal;
Expand Down
15 changes: 15 additions & 0 deletions src/resources/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { tokenStatus } from '../decoders.js';
import type { RequestOptions, TokenStatusDto } from '../models.js';
import type { Transport } from '../transport.js';

export class TokenResource {
constructor(private readonly transport: Transport) {}

/** Needs no scope and changes no data. Limited to 5 requests per 5 minutes; do not poll. */
async status(options: RequestOptions = {}): Promise<TokenStatusDto> {
return this.transport.request(
{ method: 'GET', path: '/v1/token/status', status: 200, signal: options.signal },
tokenStatus,
);
}
}
Loading