Skip to content

Commit

Permalink
accept date range parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
dangowans committed Aug 4, 2023
1 parent 4f34eef commit 8ef3ec8
Show file tree
Hide file tree
Showing 14 changed files with 194 additions and 25 deletions.
9 changes: 5 additions & 4 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type types as greenButtonTypes } from '@cityssm/green-button-parser';
import type { DateTimeFilters } from './types.js';
export interface Configuration {
baseUrl: `${string}/`;
clientId?: string;
Expand All @@ -7,8 +8,8 @@ export interface Configuration {
}
export declare function setConfiguration(configuration: Configuration): void;
export declare function setUtilityApiConfiguration(apiToken: string, baseUrl?: `${string}/`): void;
export declare function getEndpoint(endpoint: string): Promise<string | undefined>;
export declare function getGreenButtonEndpoint(greenButtonEndpoint: `/${string}`): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getEndpoint(endpoint: string, getParameters?: Record<string, string>): Promise<string | undefined>;
export declare function getGreenButtonEndpoint(greenButtonEndpoint: `/${string}`, getParameters?: Record<string, string>): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getAuthorizations(): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getAuthorization(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getUsagePoints(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
Expand All @@ -19,8 +20,8 @@ export declare function getElectricPowerQualitySummaries(authorizationId: string
export declare function getCustomers(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getCustomerAccounts(authorizationId: string, customerId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getCustomerAgreements(authorizationId: string, customerId: string, customerAccountId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getBatchSubscriptionsByAuthorization(authorizationId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getBatchSubscriptionsByMeter(authorizationId: string, meterId: string): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getBatchSubscriptionsByAuthorization(authorizationId: string, dateTimeFilters?: DateTimeFilters): Promise<greenButtonTypes.GreenButtonJson | undefined>;
export declare function getBatchSubscriptionsByMeter(authorizationId: string, meterId: string, dateTimeFilters?: DateTimeFilters): Promise<greenButtonTypes.GreenButtonJson | undefined>;
declare const _default: {
setConfiguration: typeof setConfiguration;
setUtilityApiConfiguration: typeof setUtilityApiConfiguration;
Expand Down
23 changes: 15 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { atomToGreenButtonJson } from '@cityssm/green-button-parser';
import axios from 'axios';
import Debug from 'debug';
import { formatDateTimeFiltersParameters } from './utilities.js';
const debug = Debug('green-button-subscriber');
let _configuration;
let _token;
Expand Down Expand Up @@ -42,7 +43,7 @@ async function getAccessToken() {
debug('Error getting access token:', error.response.data);
}
}
export async function getEndpoint(endpoint) {
export async function getEndpoint(endpoint, getParameters = {}) {
if (_token === undefined || Date.now() >= _token.expires_in * 1000) {
debug('Token expired.');
await getAccessToken();
Expand All @@ -52,17 +53,23 @@ export async function getEndpoint(endpoint) {
};
const apiEndpoint = _configuration.baseUrl + endpoint;
debug(`End Point: ${apiEndpoint}`);
const requestOptions = {
headers
};
if (getParameters !== undefined && Object.keys(getParameters).length > 0) {
requestOptions.params = getParameters;
}
try {
const response = await axios.get(apiEndpoint, { headers });
const response = await axios.get(apiEndpoint, requestOptions);
return response.data;
}
catch (error) {
debug('Error accessing API endpoint:', error.response.data);
}
return undefined;
}
export async function getGreenButtonEndpoint(greenButtonEndpoint) {
const greenButtonXml = await getEndpoint(`DataCustodian/espi/1_1/resource${greenButtonEndpoint}`);
export async function getGreenButtonEndpoint(greenButtonEndpoint, getParameters) {
const greenButtonXml = await getEndpoint(`DataCustodian/espi/1_1/resource${greenButtonEndpoint}`, getParameters);
if (greenButtonXml === undefined) {
return undefined;
}
Expand Down Expand Up @@ -98,11 +105,11 @@ export async function getCustomerAccounts(authorizationId, customerId) {
export async function getCustomerAgreements(authorizationId, customerId, customerAccountId) {
return await getGreenButtonEndpoint(`/RetailCustomer/${authorizationId}/Customer/${customerId}/CustomerAccount/${customerAccountId}/CustomerAgreement`);
}
export async function getBatchSubscriptionsByAuthorization(authorizationId) {
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}`);
export async function getBatchSubscriptionsByAuthorization(authorizationId, dateTimeFilters) {
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}`, formatDateTimeFiltersParameters(dateTimeFilters));
}
export async function getBatchSubscriptionsByMeter(authorizationId, meterId) {
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}/UsagePoint/${meterId}`);
export async function getBatchSubscriptionsByMeter(authorizationId, meterId, dateTimeFilters) {
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}/UsagePoint/${meterId}`, formatDateTimeFiltersParameters(dateTimeFilters));
}
export default {
setConfiguration,
Expand Down
38 changes: 29 additions & 9 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import {
atomToGreenButtonJson,
type types as greenButtonTypes
} from '@cityssm/green-button-parser'
import axios from 'axios'
import axios, { type AxiosRequestConfig } from 'axios'
import Debug from 'debug'

import type { DateTimeFilters } from './types.js'
import { formatDateTimeFiltersParameters } from './utilities.js'

const debug = Debug('green-button-subscriber')

export interface Configuration {
Expand Down Expand Up @@ -76,7 +79,8 @@ async function getAccessToken(): Promise<void> {
}

export async function getEndpoint(
endpoint: string
endpoint: string,
getParameters: Record<string, string> = {}
): Promise<string | undefined> {
if (_token === undefined || Date.now() >= _token.expires_in * 1000) {
// If the token is not obtained or has expired, get a new one
Expand All @@ -92,8 +96,16 @@ export async function getEndpoint(
const apiEndpoint = _configuration.baseUrl + endpoint
debug(`End Point: ${apiEndpoint}`)

const requestOptions: AxiosRequestConfig = {
headers
}

if (getParameters !== undefined && Object.keys(getParameters).length > 0) {
requestOptions.params = getParameters
}

try {
const response = await axios.get(apiEndpoint, { headers })
const response = await axios.get(apiEndpoint, requestOptions)
return response.data
} catch (error) {
debug('Error accessing API endpoint:', error.response.data)
Expand All @@ -103,10 +115,12 @@ export async function getEndpoint(
}

export async function getGreenButtonEndpoint(
greenButtonEndpoint: `/${string}`
greenButtonEndpoint: `/${string}`,
getParameters?: Record<string, string>
): Promise<greenButtonTypes.GreenButtonJson | undefined> {
const greenButtonXml = await getEndpoint(
`DataCustodian/espi/1_1/resource${greenButtonEndpoint}`
`DataCustodian/espi/1_1/resource${greenButtonEndpoint}`,
getParameters
)

if (greenButtonXml === undefined) {
Expand Down Expand Up @@ -244,9 +258,13 @@ export async function getCustomerAgreements(
* @returns
*/
export async function getBatchSubscriptionsByAuthorization(
authorizationId: string
authorizationId: string,
dateTimeFilters?: DateTimeFilters
): Promise<greenButtonTypes.GreenButtonJson | undefined> {
return await getGreenButtonEndpoint(`/Batch/Subscription/${authorizationId}`)
return await getGreenButtonEndpoint(
`/Batch/Subscription/${authorizationId}`,
formatDateTimeFiltersParameters(dateTimeFilters)
)
}

/**
Expand All @@ -258,10 +276,12 @@ export async function getBatchSubscriptionsByAuthorization(
*/
export async function getBatchSubscriptionsByMeter(
authorizationId: string,
meterId: string
meterId: string,
dateTimeFilters?: DateTimeFilters
): Promise<greenButtonTypes.GreenButtonJson | undefined> {
return await getGreenButtonEndpoint(
`/Batch/Subscription/${authorizationId}/UsagePoint/${meterId}`
`/Batch/Subscription/${authorizationId}/UsagePoint/${meterId}`,
formatDateTimeFiltersParameters(dateTimeFilters)
)
}

Expand Down
9 changes: 7 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ describe('node-green-button-subscriber', () => {
});
it('Retrieves batch subscriptions by authorization', async () => {
try {
const response = await greenButtonSubscriber.getBatchSubscriptionsByAuthorization(authorizationId);
const response = await greenButtonSubscriber.getBatchSubscriptionsByAuthorization(authorizationId, {
publishedMax: new Date(2023, 3 - 1, 28)
});
assert.ok(response !== undefined);
const entries = greenButtonHelpers.getEntriesByContentType(response, 'IntervalBlock');
assert.ok(entries.length > 0);
Expand All @@ -138,7 +140,10 @@ describe('node-green-button-subscriber', () => {
});
it('Retrieves batch subscriptions by meter', async () => {
try {
const response = await greenButtonSubscriber.getBatchSubscriptionsByMeter(authorizationId, meterId);
const response = await greenButtonSubscriber.getBatchSubscriptionsByMeter(authorizationId, meterId, {
publishedMin: new Date(2023, 7 - 1, 1),
publishedMax: '2023-08-31T23:59:59Z'
});
assert.ok(response !== undefined);
const entries = greenButtonHelpers.getEntriesByContentType(response, 'IntervalBlock');
assert.ok(entries.length > 0);
Expand Down
11 changes: 9 additions & 2 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ describe('node-green-button-subscriber', () => {
try {
const response =
await greenButtonSubscriber.getBatchSubscriptionsByAuthorization(
authorizationId
authorizationId,
{
publishedMax: new Date(2023, 3 - 1, 28)
}
)

assert.ok(response !== undefined)
Expand All @@ -239,7 +242,11 @@ describe('node-green-button-subscriber', () => {
try {
const response = await greenButtonSubscriber.getBatchSubscriptionsByMeter(
authorizationId,
meterId
meterId,
{
publishedMin: new Date(2023, 7 - 1, 1),
publishedMax: '2023-08-31T23:59:59Z'
}
)

assert.ok(response !== undefined)
Expand Down
1 change: 1 addition & 0 deletions test/utilities.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
14 changes: 14 additions & 0 deletions test/utilities.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import assert from 'node:assert';
import { formatDateTimeFiltersParameters } from '../utilities.js';
describe('node-green-button-subscriber/helpers', () => {
it('Formats Dates and ISO strings properly', () => {
const isoDate = '2023-01-02T12:34:56Z';
const dateTimeFilters = {
publishedMin: isoDate,
publishedMax: new Date(isoDate)
};
const parameters = formatDateTimeFiltersParameters(dateTimeFilters);
assert.strictEqual(parameters['published-min'], isoDate);
assert.strictEqual(parameters['published-max'], isoDate);
});
});
20 changes: 20 additions & 0 deletions test/utilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import assert from 'node:assert'

import type { DateTimeFilters, IsoDateString } from '../types.js'
import { formatDateTimeFiltersParameters } from '../utilities.js'

describe('node-green-button-subscriber/helpers', () => {
it('Formats Dates and ISO strings properly', () => {
const isoDate: IsoDateString = '2023-01-02T12:34:56Z'

const dateTimeFilters: DateTimeFilters = {
publishedMin: isoDate,
publishedMax: new Date(isoDate)
}

const parameters = formatDateTimeFiltersParameters(dateTimeFilters)

assert.strictEqual(parameters['published-min'], isoDate)
assert.strictEqual(parameters['published-max'], isoDate)
})
})
8 changes: 8 additions & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export type IsoDateString = `${string}-${string}-${string}T${string}:${string}:${string}Z`;
export type DateOrIsoDateString = Date | IsoDateString;
export interface DateTimeFilters {
publishedMin?: DateOrIsoDateString;
publishedMax?: DateOrIsoDateString;
updatedMin?: DateOrIsoDateString;
updatedMax?: DateOrIsoDateString;
}
1 change: 1 addition & 0 deletions types.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
11 changes: 11 additions & 0 deletions types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type IsoDateString =
`${string}-${string}-${string}T${string}:${string}:${string}Z`

export type DateOrIsoDateString = Date | IsoDateString

export interface DateTimeFilters {
publishedMin?: DateOrIsoDateString
publishedMax?: DateOrIsoDateString
updatedMin?: DateOrIsoDateString
updatedMax?: DateOrIsoDateString
}
3 changes: 3 additions & 0 deletions utilities.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import type { DateOrIsoDateString, DateTimeFilters, IsoDateString } from './types.js';
export declare function formatDateTime(dateOrIsoDateString: DateOrIsoDateString): IsoDateString;
export declare function formatDateTimeFiltersParameters(dateTimeFilters?: DateTimeFilters): Record<string, string>;
26 changes: 26 additions & 0 deletions utilities.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export function formatDateTime(dateOrIsoDateString) {
if (typeof dateOrIsoDateString === 'string') {
return dateOrIsoDateString;
}
const isoDateString = dateOrIsoDateString.toISOString();
if (isoDateString.length === 24) {
return (isoDateString.slice(0, -5) + 'Z');
}
return isoDateString;
}
export function formatDateTimeFiltersParameters(dateTimeFilters = {}) {
const parameters = {};
if (dateTimeFilters.publishedMin !== undefined) {
parameters['published-min'] = formatDateTime(dateTimeFilters.publishedMin);
}
if (dateTimeFilters.publishedMax !== undefined) {
parameters['published-max'] = formatDateTime(dateTimeFilters.publishedMax);
}
if (dateTimeFilters.updatedMin !== undefined) {
parameters['updated-min'] = formatDateTime(dateTimeFilters.updatedMin);
}
if (dateTimeFilters.updatedMax !== undefined) {
parameters['updated-max'] = formatDateTime(dateTimeFilters.updatedMax);
}
return parameters;
}
45 changes: 45 additions & 0 deletions utilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type {
DateOrIsoDateString,
DateTimeFilters,
IsoDateString
} from './types.js'

export function formatDateTime(
dateOrIsoDateString: DateOrIsoDateString
): IsoDateString {
if (typeof dateOrIsoDateString === 'string') {
return dateOrIsoDateString
}

const isoDateString = dateOrIsoDateString.toISOString()

if (isoDateString.length === 24) {
return (isoDateString.slice(0, -5) + 'Z') as IsoDateString
}

return isoDateString as IsoDateString
}

export function formatDateTimeFiltersParameters(
dateTimeFilters: DateTimeFilters = {}
): Record<string, string> {
const parameters = {}

if (dateTimeFilters.publishedMin !== undefined) {
parameters['published-min'] = formatDateTime(dateTimeFilters.publishedMin)
}

if (dateTimeFilters.publishedMax !== undefined) {
parameters['published-max'] = formatDateTime(dateTimeFilters.publishedMax)
}

if (dateTimeFilters.updatedMin !== undefined) {
parameters['updated-min'] = formatDateTime(dateTimeFilters.updatedMin)
}

if (dateTimeFilters.updatedMax !== undefined) {
parameters['updated-max'] = formatDateTime(dateTimeFilters.updatedMax)
}

return parameters
}

0 comments on commit 8ef3ec8

Please sign in to comment.