Skip to content

Commit

Permalink
fix: related-table eslint and prettier (#10)
Browse files Browse the repository at this point in the history
Co-authored-by: Fernando Pauer <[email protected]>
  • Loading branch information
fpauer and Fernando Pauer authored Nov 23, 2021
1 parent ef398b9 commit 67a7149
Show file tree
Hide file tree
Showing 25 changed files with 225 additions and 303 deletions.
4 changes: 4 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,9 @@ module.exports = {
'max-len': 0,
},
},
{
files: ['./packages/related-table/**/*'],
extends: './packages/related-table/.eslintrc.js',
},
],
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"eslint-plugin-jsx-a11y": "6.4.1",
"eslint-plugin-prettier": "4.0.0",
"eslint-plugin-react": "7.26.1",
"eslint-plugin-react-hooks": "^4.2.0",
"identity-obj-proxy": "^3.0.0",
"jest": "24.9.0",
"jest-cli": "24.9.0",
Expand Down
4 changes: 3 additions & 1 deletion packages/components/stencil.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ const { existsSync } = require('fs');

const credentials = (() => {
if (existsSync('./creds.json')) {
const { credentials: { accessKeyId, secretAccessKey, sessionToken } } = require('./creds.json');
const {
credentials: { accessKeyId, secretAccessKey, sessionToken },
} = require('./creds.json');

return {
'process.env.AWS_ACCESS_KEY_ID': JSON.stringify(accessKeyId),
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/common/predicates.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ describe('isMinimalStaticViewPort', () => {
start: new Date(),
};

expect(isMinimalStaticViewport(viewport as unknown as MinimalLiveViewport)).toBeFalse();
expect(isMinimalStaticViewport((viewport as unknown) as MinimalLiveViewport)).toBeFalse();
});

it('returns false when the start date is missing', () => {
Expand All @@ -186,6 +186,6 @@ describe('isMinimalStaticViewPort', () => {
end: new Date(),
};

expect(isMinimalStaticViewport(viewport as unknown as MinimalLiveViewport)).toBeFalse();
expect(isMinimalStaticViewport((viewport as unknown) as MinimalLiveViewport)).toBeFalse();
});
});
11 changes: 3 additions & 8 deletions packages/core/src/common/predicates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,11 @@ import { DataStream, DataType, MinimalStaticViewport, MinimalViewPortConfig } fr

export const isDefined = <T>(value: T | null | undefined): value is T => value != null;

export const isValid =
<T>(predicate: (t: Partial<T>) => boolean) =>
(t: Partial<T>): t is T =>
predicate(t);
export const isValid = <T>(predicate: (t: Partial<T>) => boolean) => (t: Partial<T>): t is T => predicate(t);

// As of now, we only check if the current component supports string or not.
export const isSupportedDataType =
(supportsString: boolean) =>
({ dataType }: { dataType: DataType }) =>
(supportsString && dataType === DataType.STRING) || dataType !== DataType.STRING;
export const isSupportedDataType = (supportsString: boolean) => ({ dataType }: { dataType: DataType }) =>
(supportsString && dataType === DataType.STRING) || dataType !== DataType.STRING;

export const isNumberDataStream = (stream: DataStream): stream is DataStream<number> =>
stream.dataType === DataType.NUMBER;
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/common/tests/mocks/assetPropertyValue.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
GetAssetPropertyValueHistoryResponse,
GetAssetPropertyValueResponse,
GetAssetPropertyAggregatesResponse
GetAssetPropertyAggregatesResponse,
} from '@aws-sdk/client-iotsitewise';

/**
Expand Down Expand Up @@ -52,19 +52,19 @@ export const AGGREGATE_VALUES: GetAssetPropertyAggregatesResponse = {
timestamp: new Date(2000, 0, 0, 1),
value: {
average: 5,
}
},
},
{
timestamp: new Date(2000, 0, 0, 2),
value: {
average: 7,
}
},
},
{
timestamp: new Date(2000, 0, 0, 3),
value: {
average: 10,
}
},
},
],
};
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/common/tests/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const createSiteWiseSDK = ({
getAssetPropertyValueHistory = jest.fn(),
getInterpolatedAssetPropertyValues = jest.fn(),
}) =>
({
(({
send: (command: { input: Object }) => {
// Mocks out the process of a sending a command within the JS AWS-SDK v3, learn more at
// https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#high-level-concepts
Expand All @@ -27,4 +27,4 @@ export const createSiteWiseSDK = ({
);
}
},
} as unknown as IoTSiteWiseClient);
} as unknown) as IoTSiteWiseClient);
22 changes: 9 additions & 13 deletions packages/core/src/data-module/data-cache/dataCacheWrapped.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,16 @@ export class DataCache {
* coordinating the dispatching of the action throughout the file.
*/

public onSuccess =
(queryConfig: Request) =>
(dataStreams: DataStream[]): void => {
const queryStart: Date = viewportStartDate(queryConfig.viewport);
const queryEnd: Date = viewportEndDate(queryConfig.viewport);
public onSuccess = (queryConfig: Request) => (dataStreams: DataStream[]): void => {
const queryStart: Date = viewportStartDate(queryConfig.viewport);
const queryEnd: Date = viewportEndDate(queryConfig.viewport);

// TODO: `duration` is not an accurate way to determine what _was_ requested.
// Need to change then code to utilize the actual start and end date, as utilized by the data source which initiated the request.
// For example, if we have queried data for the last day, but it took 1 minute for the query to resolve, we would have the start and the end date
// incorrectly offset by one minute with the correct logic.
dataStreams.forEach((stream) =>
this.dataCache.dispatch(onSuccessAction(stream.id, stream, queryStart, queryEnd))
);
};
// TODO: `duration` is not an accurate way to determine what _was_ requested.
// Need to change then code to utilize the actual start and end date, as utilized by the data source which initiated the request.
// For example, if we have queried data for the last day, but it took 1 minute for the query to resolve, we would have the start and the end date
// incorrectly offset by one minute with the correct logic.
dataStreams.forEach((stream) => this.dataCache.dispatch(onSuccessAction(stream.id, stream, queryStart, queryEnd)));
};

public onError = ({ id, resolution, error }: { id: string; resolution: Resolution; error: string }): void => {
this.dataCache.dispatch(onErrorAction(id, resolution, error));
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/data-module/data-cache/toDataStreams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const toDataStreams = ({
const streamsResolutions = dataStreamsStores[info.id] || {};
const resolutions = Object.keys(streamsResolutions);
const aggregatedData = resolutions
.map((resolution) => streamsResolutions[resolution as unknown as number])
.map((resolution) => streamsResolutions[(resolution as unknown) as number])
.filter(isDefined)
.filter(({ resolution }) => resolution > 0);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ export default class RequestScheduler {
}

this.intervalMap[id] = { start: new Date(new Date().getTime() - duration), end: new Date() };
this.intervalMap[id].intervalId = setInterval(() => {
this.intervalMap[id].intervalId = (setInterval(() => {
const newStart = new Date(Date.now() - duration);
const newEnd = new Date();

this.intervalMap[id] = { ...this.intervalMap[id], start: newStart, end: newEnd };
cb({ start: newStart, end: newEnd });
}, refreshRate) as unknown as number;
}, refreshRate) as unknown) as number;
};

public remove = (id: string): void => {
Expand Down
20 changes: 18 additions & 2 deletions packages/core/src/data-sources/site-wise/client/client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,15 @@ describe('getAggregatedPropertyDataPoints', () => {
const resolution = '1h';
const aggregateTypes = [AggregateType.AVERAGE];

await client.getAggregatedPropertyDataPoints({ query, onSuccess, onError, start: startDate, end: endDate, resolution, aggregateTypes });
await client.getAggregatedPropertyDataPoints({
query,
onSuccess,
onError,
start: startDate,
end: endDate,
resolution,
aggregateTypes,
});

expect(onError).toBeCalled();
});
Expand All @@ -181,7 +189,15 @@ describe('getAggregatedPropertyDataPoints', () => {
const resolution = '1h';
const aggregateTypes = [AggregateType.AVERAGE];

await client.getAggregatedPropertyDataPoints({ query, onSuccess, onError, start: startDate, end: endDate, resolution, aggregateTypes });
await client.getAggregatedPropertyDataPoints({
query,
onSuccess,
onError,
start: startDate,
end: endDate,
resolution,
aggregateTypes,
});

expect(getAssetPropertyAggregates).toBeCalledWith(
expect.objectContaining({ assetId, propertyId, startDate, endDate, resolution, aggregateTypes })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { GetAssetPropertyAggregatesCommand, IoTSiteWiseClient, TimeOrdering, AggregateType } from '@aws-sdk/client-iotsitewise';
import {
GetAssetPropertyAggregatesCommand,
IoTSiteWiseClient,
TimeOrdering,
AggregateType,
} from '@aws-sdk/client-iotsitewise';
import { AssetId, AssetPropertyId, SiteWiseDataStreamQuery } from '../types';
import { aggregateToDataPoint } from '../util/toDataPoint';
import { dataStreamFromSiteWise } from '../dataStreamFromSiteWise';
Expand Down
14 changes: 4 additions & 10 deletions packages/core/src/data-sources/site-wise/util/toDataPoint.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,8 @@ describe('toDataPoint', () => {
});

describe('aggregateToDataPoint', () => {
it.each([
'average',
'count',
'maximum',
'minimum',
'sum'
])('converts correctly for %s', (aggregationType) => {
const timestamp = new Date(2000,0,0);
it.each(['average', 'count', 'maximum', 'minimum', 'sum'])('converts correctly for %s', (aggregationType) => {
const timestamp = new Date(2000, 0, 0);

expect(
aggregateToDataPoint({
Expand All @@ -118,15 +112,15 @@ describe('aggregateToDataPoint', () => {
});

it('throws error when invalid aggregation type passed', () => {
const timestamp = new Date(2000,0,0);
const timestamp = new Date(2000, 0, 0);

expect(() => {
aggregateToDataPoint({
timestamp,
value: {
['someInvalidAggregationType' as any]: 100,
},
})
});
}).toThrowError();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ const getAggregateTimestamp = (timestamp?: Date) => {
}

throw new Error('Expected timestamp to be instance of Date');
}
};

/**
* Aggregates To Data Point
Expand Down
10 changes: 9 additions & 1 deletion packages/related-table/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
const fs = require('fs');
const path = require('path');

const tsConfig = fs.existsSync('tsconfig.json')
? path.resolve('tsconfig.json')
: path.resolve('./packages/related-table/tsconfig.json');

module.exports = {
ignorePatterns: ['.storybook', 'stories', 'config', 'jest.config.ts', '**/*.js'],
plugins: [
'eslint-plugin-import',
'eslint-plugin-jsx-a11y',
Expand All @@ -7,7 +15,7 @@ module.exports = {
'eslint-plugin-react-hooks',
],
parserOptions: {
project: './tsconfig.json',
project: tsConfig,
},
rules: {
'import/prefer-default-export': 'off',
Expand Down
12 changes: 4 additions & 8 deletions packages/related-table/babel.config.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
// Don't process node_modules except for AWS UI.
module.exports = {
ignore: [/node_modules\/?!@awsui\/components-react/],
presets: [
'@babel/preset-env'
],
presets: ['@babel/preset-env'],
env: {
test: {
// ...
plugins: [
'@babel/plugin-transform-runtime'
]
}
}
plugins: ['@babel/plugin-transform-runtime'],
},
},
};
6 changes: 2 additions & 4 deletions packages/related-table/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,15 @@ export default {
transform: {
'.+\\.ts$': 'ts-jest',
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest'
'^.+\\.(js|jsx)$': 'babel-jest',
},

// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
transformIgnorePatterns: [
'node_modules/(?!@awsui/components-react)/',
],
transformIgnorePatterns: ['node_modules/(?!@awsui/components-react)/'],

// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
Expand Down
4 changes: 0 additions & 4 deletions packages/related-table/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@
"eslint": "^7.29.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-config-airbnb-typescript": "^12.3.1",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.24.0",
"eslint-plugin-react-hooks": "^4.2.0",
"husky": "^6.0.0",
"jest": "^27.0.5",
"microbundle": "^0.13.3",
Expand Down
38 changes: 15 additions & 23 deletions packages/related-table/stories/AsyncData.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
import {
Header,
StatusIndicator,
StatusIndicatorProps,
} from '@awsui/components-react';
import { Header, StatusIndicator, StatusIndicatorProps } from '@awsui/components-react';
import React, { useEffect, useState } from 'react';
import { Meta, Story } from '@storybook/react';
import { RelatedTable, useTreeCollection } from '../src';
Expand Down Expand Up @@ -52,8 +48,8 @@ function genData() {
parentId: 'Equipment',
status: { state: 'ACTIVE' },
},
{ entityId: 'Mixer', parentId: 'Cookie Production Line 1', status: { state: 'ACTIVE' }, },
{ entityId: 'Pump', parentId: 'Mixer',status: { state: 'ACTIVE' } },
{ entityId: 'Mixer', parentId: 'Cookie Production Line 1', status: { state: 'ACTIVE' } },
{ entityId: 'Pump', parentId: 'Mixer', status: { state: 'ACTIVE' } },
{ entityId: 'Motor_01', parentId: 'Mixer', status: { state: 'ACTIVE' } },
{ entityId: 'Motor_02', parentId: 'Mixer', status: { state: 'ACTIVE' } },
{ entityId: 'Motor_03', parentId: 'Mixer', status: { state: 'ACTIVE' } },
Expand Down Expand Up @@ -84,18 +80,18 @@ export const AsyncData: Story = () => {
},
{
id: 'status',
header: 'Status',
header: 'Status',
cell: (item: any) => {
const currentState = item.status?.state || 'ERROR';
const statusMap: { [key: string]: StatusIndicatorProps.Type } = {
CREATING: 'in-progress',
UPDATING: 'in-progress',
DELETING: 'in-progress',
ACTIVE: 'success',
ERROR: 'error',
};
return <StatusIndicator type={statusMap[currentState]}>{currentState}</StatusIndicator>;
},
const currentState = item.status?.state || 'ERROR';
const statusMap: { [key: string]: StatusIndicatorProps.Type } = {
CREATING: 'in-progress',
UPDATING: 'in-progress',
DELETING: 'in-progress',
ACTIVE: 'success',
ERROR: 'error',
};
return <StatusIndicator type={statusMap[currentState]}>{currentState}</StatusIndicator>;
},
},
];
const { expandNode, items, collectionProps } = useTreeCollection(allItems, {
Expand All @@ -120,11 +116,7 @@ export const AsyncData: Story = () => {
items={items}
header={
<Header
counter={
selectedItems?.length
? `(${selectedItems.length}/${allItems.length})`
: `(${allItems.length})`
}
counter={selectedItems?.length ? `(${selectedItems.length}/${allItems.length})` : `(${allItems.length})`}
>
Entities
</Header>
Expand Down
Loading

0 comments on commit 67a7149

Please sign in to comment.