repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
tony-aq/optic
|
workspaces/ui-v2/src/store/diff/thunks.ts
|
import { v4 as uuidv4 } from 'uuid';
import * as Sentry from '@sentry/react';
import { createAsyncThunk } from '@reduxjs/toolkit';
import { IAffordanceTrailsDiffHashMap } from '@useoptic/cli-shared/build/diffs/initial-types';
import {
IOpticCapturesService,
IOpticDiffService,
IUnrecognizedUrl,
} from '@useoptic/spectacle';
import { ParsedDiff } from '<src>/lib/parse-diff';
import { RootState, AppDispatch } from '../root';
export const fetchDiffsForCapture = createAsyncThunk<
{
data: {
diffs: ParsedDiff[];
urls: IUnrecognizedUrl[];
trails: IAffordanceTrailsDiffHashMap;
};
diffService: IOpticDiffService;
numberOfEndpoints: number;
},
{
capturesService: IOpticCapturesService;
captureId: string;
},
{
dispatch: AppDispatch;
state: RootState;
}
>(
'FETCH_DIFFS_FOR_CAPTURE',
async ({ capturesService, captureId }, thunkApi) => {
const diffId = uuidv4();
try {
const startDiffResult = await capturesService.startDiff(
diffId,
captureId
);
const diffService = await startDiffResult.onComplete;
const diffsPromise = diffService.listDiffs();
const trailsPromise = diffService.learnShapeDiffAffordances();
const urlsPromise = diffService.listUnrecognizedUrls();
const [diffs, trails, urls] = await Promise.all([
diffsPromise,
trailsPromise,
urlsPromise,
]);
const parsedDiffs = diffs.diffs.map(
(i: any) => new ParsedDiff(i[0], i[1], i[2])
);
return {
data: {
diffs: parsedDiffs,
urls: urls.urls,
trails,
},
diffService,
numberOfEndpoints: (
thunkApi.getState().endpoints.results.data?.endpoints || []
).length,
};
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
}
);
|
tony-aq/optic
|
workspaces/cli-server/src/sessions.ts
|
<reponame>tony-aq/optic<gh_stars>100-1000
export class SessionsManager {
private sessions: Session[] = [];
private create(path: string) {
let id = '' + (this.sessions.length + 1);
let session = new Session(id, path);
this.sessions.push(session);
return session;
}
async start(path: string): Promise<Session> {
let existingSession = this.sessions.find(
(session) => path && session.path === path
);
let session = existingSession || this.create(path);
await session.start();
return session;
}
findById(sessionId: string): Session | undefined {
return (
(sessionId &&
this.sessions.find((session) => session.id === sessionId)) ||
undefined
);
}
}
export class Session {
constructor(readonly id: string, readonly path: string) {}
async start() {}
async stop() {}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/selectors/index.ts
|
<filename>workspaces/ui-v2/src/store/selectors/index.ts
export * from './documentationEditSelectors';
export * from './endpointSelectors';
export * from './shapeSelectors';
export * from './visibilitySelectors';
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/diff-description-interpreter.ts
|
<reponame>tony-aq/optic
import { BodyShapeDiff, ParsedDiff, DiffLocation } from './parse-diff';
import {
BodyPreview,
CurrentSpecContext,
IChangeType,
IDiffDescription,
} from './Interfaces';
import { getExpectationsForShapeTrail } from './shape-diff-dsl-rust';
import { code, ICopy, plain } from '<src>/pages/diffs/components/ICopyRender';
import { IJsonObjectKey } from '@useoptic/cli-shared/build/diffs/json-trail';
import { ICoreShapeKinds, IHttpInteraction } from '@useoptic/optic-domain';
import { toJsonExample } from '@useoptic/shape-hash';
import { namer, nameForCoreShapeKind } from './quick-namer';
const getJsonBodyToPreview = (
location: DiffLocation,
interaction: IHttpInteraction
): BodyPreview => {
const body =
(location.isQueryParameter() && interaction.request.query) ||
(location.isRequest() && interaction.request.body.value) ||
(location.isResponse() && interaction.response.body.value);
if (body) {
const { shapeHashV1Base64, asText, asJsonString } = body;
if (asJsonString && !location.isQueryParameter()) {
return {
asJson: JSON.parse(asJsonString),
asText: null,
noBody: false,
empty: false,
};
}
if (shapeHashV1Base64 && !location.isQueryParameter()) {
return {
asJson: toJsonExample(shapeHashV1Base64),
asText: null,
noBody: false,
empty: false,
};
}
if (asText) {
return { asJson: null, asText: asText, noBody: false, empty: false };
}
return { asJson: null, asText: null, noBody: false, empty: true };
} else {
return { asJson: null, asText: null, noBody: true, empty: false };
}
};
export function descriptionForNewRegions(
diff: ParsedDiff,
location: DiffLocation
): IDiffDescription {
let title: ICopy[] = [];
if (location.isQueryParameter()) {
title = [plain('undocumented query parameters observed')];
}
const requestDescriptor = location.getRequestDescriptor();
if (requestDescriptor) {
title = [
plain('undocumented'),
code(requestDescriptor.contentType),
plain('request observed'),
];
}
const responseDescriptor = location.getResponseDescriptor();
if (responseDescriptor) {
title = [
plain('undocumented'),
code(responseDescriptor.statusCode.toString()),
plain('response with'),
code(responseDescriptor.contentType || 'No Body'),
plain('observed'),
];
}
return {
title,
changeType: IChangeType.Added,
location,
diffHash: diff.diffHash,
assertion: [plain('Undocumented Body Observed')],
getJsonBodyToPreview: getJsonBodyToPreview.bind(null, location),
};
}
export async function descriptionForShapeDiff(
asShapeDiff: BodyShapeDiff,
query: any,
currentSpecContext: CurrentSpecContext
): Promise<IDiffDescription> {
const location = asShapeDiff.location;
const jsonTrailPath = asShapeDiff.jsonTrail.path;
const jsonTrailLast = jsonTrailPath[jsonTrailPath.length - 1]!;
const expected = await getExpectationsForShapeTrail(
asShapeDiff.shapeTrail,
asShapeDiff.jsonTrail,
query,
currentSpecContext
);
//root handler
if (jsonTrailPath.length === 0) {
return {
title: [plain('root shape did not match'), code(expected.shapeName())],
location,
changeType: IChangeType.Changed,
assertion: [plain('expected'), code(expected.shapeName())],
diffHash: asShapeDiff.diffHash(),
getJsonBodyToPreview: getJsonBodyToPreview.bind(null, location),
};
}
//known field handler
if (expected.isField()) {
if (asShapeDiff.isUnmatched) {
let shapeName = location.isQueryParameter()
? namer(Array.from(expected.expectedShapes()), (kind) => {
if (kind === ICoreShapeKinds.ListKind) {
return 'multiple';
} else {
return nameForCoreShapeKind(kind);
}
})
: expected.shapeName();
return {
title: [
plain('values of '),
code(expected.fieldKey()),
plain('did not match'),
code(shapeName),
],
location,
changeType: IChangeType.Changed,
diffHash: asShapeDiff.diffHash(),
assertion: [plain('expected'), code(shapeName)],
getJsonBodyToPreview: getJsonBodyToPreview.bind(null, location),
};
}
}
//undocumented field handler
const lastIsField = (jsonTrailLast as IJsonObjectKey).JsonObjectKey;
if (asShapeDiff.isUnspecified && lastIsField) {
const undocumentedLocation = location.isQueryParameter()
? 'undocumented query parameter'
: 'undocumented field';
return {
title: [
plain(undocumentedLocation),
code(lastIsField.key),
plain('observed'),
],
location,
changeType: IChangeType.Added,
diffHash: asShapeDiff.diffHash(),
assertion: [code(undocumentedLocation)],
getJsonBodyToPreview: getJsonBodyToPreview.bind(null, location),
};
}
//list item handler
if (expected.isListItemShape()) {
return {
title: [plain('list items did not match'), code(expected.shapeName())],
location,
changeType: IChangeType.Changed,
diffHash: asShapeDiff.diffHash(),
assertion: [plain('expected'), code(expected.shapeName())],
getJsonBodyToPreview: getJsonBodyToPreview.bind(null, location),
};
}
//we shouldn't ever get there
return {
title: [plain('unknown diff kind')],
location,
changeType: IChangeType.Changed,
assertion: [],
unknownDiffBehavior: true,
diffHash: asShapeDiff.diffHash(),
getJsonBodyToPreview: getJsonBodyToPreview.bind(null, location),
};
}
|
tony-aq/optic
|
workspaces/snapshot-tests/src/tasks/EventsToRfcState/index.ts
|
import {
ITaskExecutor,
ITaskExecutorDependencies,
ITaskSpecification,
ITaskSpecificationInputs,
TaskType,
} from '..';
import * as opticEngine from '@useoptic/optic-engine-wasm';
import {
EventsFileToJsTaskOutput,
EventsFileToJsTaskSpecification,
} from '../EventsFileToJsTaskSpecification';
export interface IRfcEvent {}
const eventsFromFileKey = 'eventsFromFile';
export interface EventsToRfcStateTaskInputs extends ITaskSpecificationInputs {
[eventsFromFileKey]: EventsFileToJsTaskSpecification;
}
export interface EventsToRfcStateTaskDependencies
extends ITaskExecutorDependencies {
[eventsFromFileKey]: EventsFileToJsTaskOutput;
}
export interface EventsToRfcStateTaskSpecification extends ITaskSpecification {
type: TaskType.EventsToRfcStateTaskSpecification;
inputs: EventsToRfcStateTaskInputs;
}
export interface EventsToRfcStateTaskOutput {
shapesProjection: IShapesProjection;
}
export interface IShapesProjection {}
export const buildRfcStateFromEvents: ITaskExecutor<
EventsToRfcStateTaskSpecification,
EventsToRfcStateTaskDependencies,
EventsToRfcStateTaskOutput
> = async function (task, dependencies) {
const events = dependencies[eventsFromFileKey].events;
const spec = opticEngine.spec_from_events(JSON.stringify(events));
const shapesProjection = JSON.parse(opticEngine.get_shapes_projection(spec));
return Promise.resolve({ shapesProjection });
};
|
tony-aq/optic
|
workspaces/ui-v2/src/hooks/useOpticEngine.tsx
|
<reponame>tony-aq/optic
import React, { ReactNode, useContext, useEffect, useState } from 'react';
import { IOpticEngine } from '@useoptic/spectacle';
import { InvariantViolationError } from '<src>/errors';
const OpticEngineContext = React.createContext<IOpticEngine | null>(null);
export function OpticEngineStore(props: { children: ReactNode }) {
const [opticEngine, setOpticEngine] = useState<IOpticEngine | null>(null);
useEffect(() => {
async function task() {
const opticEngine = await import('@useoptic/optic-engine-wasm/browser');
setOpticEngine(opticEngine);
}
task();
}, []);
if (!opticEngine) {
//@aidan todo
return <div>loading...</div>;
}
return (
<OpticEngineContext.Provider
children={props.children}
value={opticEngine}
/>
);
}
export function useOpticEngine(): IOpticEngine {
const value = useContext(OpticEngineContext);
if (!value) {
throw new InvariantViolationError(
'useOpticEngine could not find OpticEngineContext'
);
}
return value;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/navigation/TopNavigation.tsx
|
import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { SubtleBlueBackground, SubtleGreyBackground } from '<src>/styles';
import { Container } from '@material-ui/core';
import { NavButton } from './NavButton';
import {
ChangeHistory as ChangeHistoryIcon,
Subject as SubjectIcon,
Schedule as ScheduleIcon,
} from '@material-ui/icons';
import {
useDiffReviewPageLink,
useDocumentationPageLink,
useChangelogHistoryPage,
} from './Routes';
import { useAppConfig } from '<src>/contexts/config/AppConfiguration';
import { useAppSelector } from '<src>/store';
export function TopNavigation(props: { AccessoryNavigation?: any }) {
const classes = useStyles();
const apiName = useAppSelector((state) => state.metadata.data?.apiName || '');
const appConfig = useAppConfig();
const documentationPage = useDocumentationPageLink();
const changelogHistoryPage = useChangelogHistoryPage();
const diffsPage = useDiffReviewPageLink();
const { AccessoryNavigation } = props;
return (
<div>
<div className={classes.root} key="top-navigation">
<Container maxWidth={false} style={{ paddingLeft: 0, paddingRight: 0 }}>
<AppBar position="static" color="transparent" elevation={0}>
<Toolbar className={classes.toolbar}>
<div className={classes.stacked}>
<Typography
className={classes.title}
variant="subtitle2"
noWrap
component="span"
>
{apiName}
</Typography>
<NavButton
title="Docs"
to={documentationPage.linkTo()}
Icon={SubjectIcon}
/>
{appConfig.allowEditing && (
<NavButton
title="Diffs"
to={diffsPage.linkTo()}
Icon={ChangeHistoryIcon}
/>
)}
<NavButton
title="History"
to={changelogHistoryPage.linkTo()}
Icon={ScheduleIcon}
/>
</div>
<div className={classes.spacer} />
<div>{AccessoryNavigation && <AccessoryNavigation />}</div>
</Toolbar>
</AppBar>
</Container>
</div>
<div className={classes.spacing}></div>
</div>
);
}
const useStyles = makeStyles((theme) => ({
root: {
height: '40px !important',
minHeight: 'auto !important',
zIndex: 1000,
borderBottom: `1px solid ${SubtleGreyBackground}`,
backgroundColor: SubtleBlueBackground,
position: 'fixed',
width: '100%',
},
spacing: {
height: 41, //40px height + 1px border
width: '100%',
},
toolbar: {
height: '40px !important',
minHeight: 'auto !important',
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
paddingLeft: 15,
paddingRight: 0,
paddingTop: theme.spacing(0),
paddingBottom: theme.spacing(0),
},
title: {
fontSize: 16,
marginRight: 10,
color: '#4f566b',
},
stacked: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
},
spacer: {
flex: 1,
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/components/navigation/index.ts
|
<gh_stars>100-1000
export * from './NavButton';
export * from './Routes';
export * from './TopNavigation';
|
tony-aq/optic
|
workspaces/cli-shared/src/diffs/request-spec-trail.ts
|
<filename>workspaces/cli-shared/src/diffs/request-spec-trail.ts
export type IRequestSpecTrail =
| ISpecRoot
| ISpecPath
| ISpecRequestBody
| ISpecRequestRoot
| ISpecResponseBody
| ISpecResponseRoot
| ISpecQueryParameters;
interface ISpecQueryParameters {
SpecQueryParameters: {
queryParametersId: string;
};
}
interface ISpecResponseBody {
SpecResponseBody: {
responseId: string;
};
}
interface ISpecRequestRoot {
SpecRequestRoot: {
requestId: string;
};
}
interface ISpecPath {
SpecPath: {
pathId: string;
};
}
interface ISpecRequestBody {
SpecRequestBody: {
requestId: string;
};
}
interface ISpecResponseRoot {
SpecResponseRoot: {
responseId: string;
};
}
interface ISpecRoot {
SpecRoot: {};
}
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/shape-diffs/field.ts
|
import { BodyShapeDiff } from '../parse-diff';
import { Actual, Expectation } from '../shape-diff-dsl-rust';
import sortBy from 'lodash.sortby';
import {
CurrentSpecContext,
IDiffDescription,
IInteractionPreviewTab,
IInterpretation,
IPatchChoices,
} from '../Interfaces';
import { IShapeTrail } from '@useoptic/cli-shared/build/diffs/shape-trail';
import { IJsonTrail } from '@useoptic/cli-shared/build/diffs/json-trail';
import { IAffordanceTrails } from '@useoptic/cli-shared/build/diffs/initial-types';
import { code, plain } from '<src>/pages/diffs/components/ICopyRender';
import { builderInnerShapeFromChoices } from './build-inner-shape';
import {
AddField,
FieldShapeFromShape,
ICoreShapeKinds,
SetFieldShape,
CQRSCommand,
} from '@useoptic/optic-domain';
export function fieldShapeDiffInterpreter(
shapeDiff: BodyShapeDiff,
actual: Actual,
expected: Expectation,
diffDescription: IDiffDescription,
currentSpecContext: CurrentSpecContext
): IInterpretation {
const { shapeTrail, jsonTrail } = shapeDiff;
const isUnmatched = shapeDiff.isUnmatched;
const isUnspecified = shapeDiff.isUnspecified;
const present = new FieldShapeInterpretationHelper(
shapeDiff.diffHash(),
shapeTrail,
jsonTrail,
actual.learnedTrails,
actual,
expected,
diffDescription
);
let updateSpecChoices: IPatchChoices = {
copy: [],
shapes: [],
isField: true,
isQueryParam: shapeDiff.location.isQueryParameter(),
};
// field is in the spec, the value was not what we expected to see
if (isUnmatched) {
const unexpectedShapesObserved = expected.diffActual(actual);
const observedShapeDidNotMatch = unexpectedShapesObserved.length > 0;
if (actual.wasMissing() && expected.aRequiredField()) {
updateSpecChoices.copy = [
plain('what values are allowed for'),
code(actual.fieldKey()!),
];
updateSpecChoices.isOptional = true;
updateSpecChoices.shapes = sortBy(
expected
.unionWithActual(actual)
.filter((i) => {
return i !== ICoreShapeKinds.OptionalKind;
})
.map((i) => {
return {
coreShapeKind: i,
isValid: true,
};
}),
'isValid'
);
// present.askMakeOptional();
// present.askRemoveField();
} else if (observedShapeDidNotMatch) {
updateSpecChoices.copy = [code(actual.fieldKey()!), plain('can be a')];
updateSpecChoices.isOptional = !expected.aRequiredField();
updateSpecChoices.shapes = sortBy(
expected
.unionWithActual(actual)
.filter((i) => {
return i !== ICoreShapeKinds.OptionalKind;
})
.map((i) => {
return {
coreShapeKind: i,
isValid: true,
};
}),
'isValid'
);
// present.addAdditionalCoreShapeKinds(unexpectedShapesObserved);
}
}
// we've already check if isField() is true, so this is always add field
if (isUnspecified) {
updateSpecChoices.shapes = sortBy(
Array.from(actual.observedCoreShapeKinds()).map((i) => {
return {
coreShapeKind: i,
isValid: true,
};
}),
'isValid'
);
updateSpecChoices.isOptional = actual.wasMissing();
}
return {
previewTabs: present.createPreviews(
isUnspecified,
!!updateSpecChoices.isQueryParam
),
diffDescription,
toCommands(choices: IPatchChoices): CQRSCommand[] {
if (!choices) {
return [];
}
if (isUnmatched) {
const { commands, rootShapeId } = builderInnerShapeFromChoices(
choices,
expected.allowedCoreShapeKindsByShapeId(),
actual,
currentSpecContext
);
return [
...commands,
SetFieldShape(FieldShapeFromShape(expected.fieldId()!, rootShapeId)),
];
} else if (isUnspecified) {
const fieldId = currentSpecContext.domainIds.newFieldId();
const { commands, rootShapeId } = builderInnerShapeFromChoices(
choices,
{}, //always empty, unspecified
actual,
currentSpecContext
);
const lastObject = expected.lastObject();
return [
...commands,
AddField(
fieldId,
lastObject,
actual.fieldKey()!,
FieldShapeFromShape(fieldId, rootShapeId)
),
];
}
return [];
},
updateSpecChoices,
};
// return present.flush();
}
class FieldShapeInterpretationHelper {
private additionalCoreShapeKinds: ICoreShapeKinds[] = [];
constructor(
private diffHash: string,
private shapeTrail: IShapeTrail,
private jsonTrail: IJsonTrail,
private learnedTrails: IAffordanceTrails,
private actual: Actual,
private expected: Expectation,
private diffDescription: IDiffDescription
) {}
///////////////////////////////////////////////////////////////////
public createPreviews(
isUnspecified: boolean,
isQueryParam: boolean
): IInteractionPreviewTab[] {
const previews: IInteractionPreviewTab[] = [];
const expected = this.expected.expectedShapes();
const asFieldType =
this.expected.isField() && !this.expected.isOptionalField()
? ' required'
: '';
this.actual.interactionsGroupedByCoreShapeKind().forEach((i) => {
previews.push({
title:
isQueryParam && i.kind === ICoreShapeKinds.ListKind
? 'multiple'
: i.label,
invalid: isUnspecified ? true : !expected.has(i.kind),
interactionPointers: i.interactions,
assertion: [
plain('expected' + asFieldType),
code(this.expected.shapeName()),
],
jsonTrailsByInteractions: i.jsonTrailsByInteractions,
});
});
return orderTabs(isUnspecified, previews);
}
}
function orderTabs(newField: boolean, tabs: IInteractionPreviewTab[]) {
const ordering = {
missing: 10,
};
return tabs.sort((a, b) => {
// @ts-ignore
const aI = ordering[a.title] || 0;
// @ts-ignore
const bI = ordering[b.title] || 0;
if (aI > bI) {
return 1;
} else {
return -1;
}
});
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/components/SimulatedDiffPreview.tsx
|
<reponame>tony-aq/optic<filename>workspaces/ui-v2/src/pages/diffs/components/SimulatedDiffPreview.tsx
import React, { FC } from 'react';
import { CQRSCommand } from '@useoptic/optic-domain';
import { SimulatedCommandStore } from '<src>/components';
import { useSpectacleContext } from '<src>/contexts/spectacle-provider';
import { useFetchEndpoints } from '<src>/hooks/useFetchEndpoints';
const DataFetcherComponent: FC<{ batchId?: string }> = ({
children,
batchId,
}) => {
useFetchEndpoints(batchId);
return <>{children}</>;
};
type SimualtedDiffPreviewProps = {
previewCommands: CQRSCommand[];
};
export const SimulatedDiffPreview: FC<SimualtedDiffPreviewProps> = ({
previewCommands,
children,
}) => {
const spectacle = useSpectacleContext();
return (
<SimulatedCommandStore
spectacle={spectacle}
previewCommands={previewCommands}
>
{(batchId) => (
<DataFetcherComponent batchId={batchId}>
{children}
</DataFetcherComponent>
)}
</SimulatedCommandStore>
);
};
|
tony-aq/optic
|
workspaces/ui-v2/src/store/selectors/visibilitySelectors.ts
|
import { ChangeType } from '<src>/types';
export const isItemVisible = <T extends { isRemoved: boolean }>(
item: T
): boolean => {
return !item.isRemoved;
};
export const isItemVisibleForChangelog = <T extends { isRemoved: boolean }>(
item: T,
changes: Record<string, ChangeType>,
getId: (item: T) => string
): boolean => {
const itemId = getId(item);
// Assumption - if an item is removed, but this batch of changes contains _any_ change for this item
// we should show this item - the last change you could make is a removal
// Two assumptions:
// - You cannot un-remove a specific item (with history, you can undo batches)
// - You must always view changes compared to the latest version
return !(item.isRemoved && !changes[itemId]);
};
export const filterRemovedItems = <T extends { isRemoved: boolean }>(
removableItems: T[]
): T[] => removableItems.filter(isItemVisible);
export const filterRemovedItemForChangelog = <T extends { isRemoved: boolean }>(
removableItems: T[],
changes: Record<string, ChangeType>,
getId: (item: T) => string
): (T & { changes: ChangeType | null })[] => {
// Filter removed items that have no changes to display
const filteredItems = removableItems.filter((item) =>
isItemVisibleForChangelog(item, changes, getId)
);
const itemsWithChanges = filteredItems.map((item) => ({
...item,
changes: changes[getId(item)] || null,
}));
return itemsWithChanges;
};
export const filterMapOfRemovedItems = <T extends { isRemoved: boolean }>(
removableItemsMap: Record<string, T[]>
): Record<string, T[]> => {
const filteredMap: Record<string, T[]> = {};
for (const [key, removableItems] of Object.entries(removableItemsMap)) {
const filteredItems = filterRemovedItems(removableItems);
if (filteredItems.length > 0) {
filteredMap[key] = filteredItems;
}
}
return filteredMap;
};
export const filterMapOfRemovedItemsForChangelog = <
T extends { isRemoved: boolean }
>(
removableItemsMap: Record<string, T[]>,
changes: Record<string, ChangeType>,
getId: (item: T) => string
): Record<string, (T & { changes: ChangeType | null })[]> => {
const filteredMap: Record<
string,
(T & { changes: ChangeType | null })[]
> = {};
for (const [key, removableItems] of Object.entries(removableItemsMap)) {
const filteredItems = filterRemovedItemForChangelog(
removableItems,
changes,
getId
);
if (filteredItems.length > 0) {
filteredMap[key] = filteredItems;
}
}
return filteredMap;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/__tests/stable-path-batch-generator.test.ts
|
import { generatePathCommands } from '<src>/lib/stable-path-batch-generator';
import { IPendingEndpoint } from '<src>/pages/diffs/contexts/SharedDiffState';
import { buildUniverse } from '<src>/lib/__tests/diff-helpers/universes/buildUniverse';
import { AllPathsQuery } from '<src>/store/paths/thunks';
const gitHubExample = [
'/users/:username/orgs',
'/users/:username/recieved_events',
'/repos/:orgOrUser/:repo',
'/repos/:orgOrUser/:repo/deployments/:deploymentId',
'/users/:username',
'/license/:licence',
'/repos/:orgOrUser/:repo/deployments/:deploymentId',
'/users/:username',
'/license/:licence',
];
const pendingEndpoints: IPendingEndpoint[] = gitHubExample.map((i, index) => {
const a: IPendingEndpoint = {
ref: undefined,
staged: false,
pathPattern: i,
id: 'pending_' + index.toString(),
matchesPattern: (a, b) => false,
method: index > 4 ? 'GET' : 'POST',
};
return a;
});
test('can match pending endpoints to pathIds for empty spec', async () => {
const universe = await buildUniverse({
session: { samples: [] },
events: [],
});
const results = await generatePathCommands(
pendingEndpoints,
universe.currentSpecContext
);
const spectacle = await universe.forkSpectacleWithCommands(results.commands);
expect(results).toMatchSnapshot();
expect(await getPathsInSpec(spectacle)).toMatchSnapshot();
});
test('can match pending endpoints to pathIds in existing spec', async () => {
const universe = await buildUniverse({
session: { samples: [] },
events: [
{
BatchCommitStarted: {
batchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
commitMessage: '',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'b512abb9-3fb9-4b11-814b-bd99d7a3a2ea',
clientCommandBatchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
createdAt: '2021-05-11T16:39:01.349Z',
},
},
},
{
PathComponentAdded: {
pathId: 'path_gRFd6gar3R',
parentPathId: 'root',
name: 'users',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'b512abb9-3fb9-4b11-814b-bd99d7a3a2ea',
clientCommandBatchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
createdAt: '2021-05-11T16:39:01.353Z',
},
},
},
{
PathParameterAdded: {
pathId: 'path_IvuyljKjYc',
parentPathId: 'path_gRFd6gar3R',
name: 'username',
eventContext: null,
},
},
{
PathComponentAdded: {
pathId: 'path_VtujorMip3',
parentPathId: 'path_IvuyljKjYc',
name: 'orgs',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'b512abb9-3fb9-4b11-814b-bd99d7a3a2ea',
clientCommandBatchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
createdAt: '2021-05-11T16:39:01.356Z',
},
},
},
{
PathComponentAdded: {
pathId: 'path_mN3kTKvX5V',
parentPathId: 'path_IvuyljKjYc',
name: 'received_events',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'b512abb9-3fb9-4b11-814b-bd99d7a3a2ea',
clientCommandBatchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
createdAt: '2021-05-11T16:39:01.356Z',
},
},
},
{
PathComponentAdded: {
pathId: 'path_h5XuCUyuux',
parentPathId: 'root',
name: 'repos',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'b512abb9-3fb9-4b11-814b-bd99d7a3a2ea',
clientCommandBatchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
createdAt: '2021-05-11T16:39:01.356Z',
},
},
},
{
BatchCommitEnded: {
batchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'b512abb9-3fb9-4b11-814b-bd99d7a3a2ea',
clientCommandBatchId: '4409995b-11e6-409f-9d33-bbd82f52a279',
createdAt: '2021-05-11T16:39:01.823Z',
},
},
},
],
});
const results = await generatePathCommands(
pendingEndpoints,
universe.currentSpecContext
);
const spectacle = await universe.forkSpectacleWithCommands(results.commands);
expect(results).toMatchSnapshot();
expect(await getPathsInSpec(spectacle)).toMatchSnapshot();
});
async function getPathsInSpec(spectacle: any) {
const results = await spectacle.queryWrapper({
query: AllPathsQuery,
variables: {},
});
return results.data;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelog/components/ChangelogBackground.tsx
|
import { makeStyles, darken } from '@material-ui/core';
import {
AddedGreenBackground,
AddedGreen,
ChangedYellow,
ChangedYellowBackground,
RemovedRed,
RemovedRedBackground,
} from '<src>/styles';
// TODO generalize this style and move this into theme
export const useChangelogStyles = makeStyles(() => ({
added: {
backgroundColor: AddedGreenBackground,
borderLeft: `2px solid ${AddedGreen}`,
'&.Mui-focusVisible, &:hover': {
backgroundColor: darken(AddedGreenBackground, 0.2),
},
},
updated: {
backgroundColor: ChangedYellowBackground,
borderLeft: `2px solid ${ChangedYellow}`,
'&.Mui-focusVisible, &:hover': {
backgroundColor: darken(ChangedYellowBackground, 0.2),
},
},
removed: {
backgroundColor: RemovedRedBackground,
borderLeft: `2px solid ${RemovedRed}`,
'&.Mui-focusVisible, &:hover': {
backgroundColor: darken(RemovedRedBackground, 0.2),
},
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelog/ChangelogEndpointRootPage.tsx
|
import React, { FC } from 'react';
import { Redirect, RouteComponentProps } from 'react-router-dom';
import { LinearProgress, Typography, makeStyles } from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import ReactMarkdown from 'react-markdown';
import {
EndpointName,
PathParameters,
PageLayout,
FullWidth,
FieldOrParameter,
ShapeFetcher,
QueryParametersPanel,
ContributionsList,
HttpBodyPanel,
HttpBodySelector,
Panel,
FieldViewer,
} from '<src>/components';
import { useChangelogPages } from '<src>/components/navigation/Routes';
import { SubtleBlueBackground, FontFamily } from '<src>/styles';
import { selectors, useAppSelector } from '<src>/store';
import { getEndpointId } from '<src>/utils';
import { EndpointTOC } from '<src>/pages/docs/components';
import {
ChangelogPageAccessoryNavigation,
ValidateBatchId,
} from './components';
export const ChangelogEndpointRootPage: FC<
RouteComponentProps<{
batchId: string;
pathId: string;
method: string;
}>
> = (props) => {
return (
<PageLayout AccessoryNavigation={ChangelogPageAccessoryNavigation}>
<ValidateBatchId batchId={props.match.params.batchId}>
<ChangelogRootComponent {...props} />
</ValidateBatchId>
</PageLayout>
);
};
const ChangelogRootComponent: FC<
RouteComponentProps<{
pathId: string;
method: string;
batchId: string;
}>
> = ({ match }) => {
const { pathId, method, batchId } = match.params;
const classes = useStyles();
const changelogPageLink = useChangelogPages();
const endpointsState = useAppSelector((state) => state.endpoints.results);
const thisEndpoint = useAppSelector(
selectors.getEndpoint({ pathId, method })
);
const endpointChanges = useAppSelector(
(state) => state.endpoints.results.data?.changes || {}
);
const endpointWithChanges = selectors.filterRemovedItemForChangelog(
thisEndpoint ? [thisEndpoint] : [],
endpointChanges,
(endpoint) => getEndpointId(endpoint)
);
const visibleQueryParameters =
thisEndpoint &&
thisEndpoint.query &&
selectors.isItemVisibleForChangelog(
thisEndpoint.query,
endpointChanges,
(query) => query.queryParametersId
)
? thisEndpoint.query
: null;
const visibleRequests = selectors.filterRemovedItemForChangelog(
thisEndpoint ? thisEndpoint.requests : [],
endpointChanges,
(request) => request.requestId
);
const visibleResponsesByStatusCode = selectors.filterMapOfRemovedItemsForChangelog(
thisEndpoint ? thisEndpoint.responsesByStatusCode : {},
endpointChanges,
(response) => response.responseId
);
const isEndpointRemoved = thisEndpoint && endpointWithChanges.length === 0;
const isEndpointRemovedInThisBatch =
endpointWithChanges.length > 0 &&
endpointWithChanges[0].changes === 'removed';
if (endpointsState.loading) {
return <LinearProgress variant="indeterminate" />;
}
if (endpointsState.error) {
return <>error loading endpoint changelog information</>;
}
if (!thisEndpoint) {
return <>no endpoint here</>;
}
if (isEndpointRemoved) {
return <Redirect to={changelogPageLink.linkTo(batchId)} />;
}
const endpointId = getEndpointId(thisEndpoint);
const parameterizedPathParts = thisEndpoint.pathParameters.filter(
(path) => path.isParameterized
);
return (
<>
{isEndpointRemovedInThisBatch && (
<Alert severity="error" className={classes.removedInfoHeader}>
This endpoint has been removed
</Alert>
)}
<FullWidth style={{ paddingTop: 30, paddingBottom: 400 }}>
<Typography className={classes.regularField}>
{thisEndpoint.purpose || 'Unnamed Endpoint'}
</Typography>
<EndpointName
fontSize={19}
leftPad={0}
method={thisEndpoint.method}
fullPath={thisEndpoint.fullPath}
/>
<div className={classes.bodyContainer}>
<div className={classes.bodyDetails}>
<div>
<ReactMarkdown
className={classes.contents}
source={thisEndpoint.description}
/>
</div>
<div className={classes.panel}>
<Panel
header={
<EndpointName
fontSize={14}
leftPad={0}
method={thisEndpoint.method}
fullPath={thisEndpoint.fullPath}
/>
}
>
<PathParameters parameters={parameterizedPathParts} />
<div
style={{
marginTop: 10,
backgroundColor: SubtleBlueBackground,
borderTop: '1px solid #e2e2e2',
}}
>
<EndpointTOC
query={visibleQueryParameters}
requests={visibleRequests}
responsesByStatusCode={visibleResponsesByStatusCode}
/>
</div>
</Panel>
</div>
</div>
</div>
{visibleQueryParameters && (
<div className={classes.bodyContainer} id="query-parameters">
<div className={classes.bodyHeaderContainer}>
<h6 className={classes.bodyHeader}>Query Parameters</h6>
<ReactMarkdown
className={classes.contents}
source={visibleQueryParameters.description}
/>
</div>
<ShapeFetcher
rootShapeId={visibleQueryParameters.rootShapeId}
endpointId={endpointId}
changesSinceBatchCommit={batchId}
>
{(shapes, fields) => (
<div className={classes.bodyDetails}>
<div>
{process.env.REACT_APP_FF_FIELD_LEVEL_EDITS !== 'true' ? (
<ContributionsList
renderField={(field) => (
<FieldOrParameter
key={
field.contribution.id +
field.contribution.contributionKey
}
name={field.name}
shapes={field.shapes}
depth={field.depth}
value={field.contribution.value}
required={field.required}
/>
)}
fieldDetails={fields}
/>
) : (
<FieldViewer fields={fields} />
)}
</div>
<div className={classes.panel}>
<QueryParametersPanel
parameters={selectors.convertShapeToQueryParameters(
shapes
)}
/>
</div>
</div>
)}
</ShapeFetcher>
</div>
)}
{visibleRequests.length > 0 && (
<div className={classes.bodyContainer} id="request-body">
<div className={classes.bodyHeaderContainer}>
<h6 className={classes.bodyHeader}>Request Body</h6>
</div>
<HttpBodySelector
items={visibleRequests}
getDisplayName={(request) =>
request.body?.contentType || 'No Body'
}
>
{(request) => (
<>
<div className={classes.bodyContributionContainer}>
<ReactMarkdown
className={classes.contents}
source={request.description}
/>
</div>
{request.body ? (
<ShapeFetcher
rootShapeId={request.body.rootShapeId}
endpointId={endpointId}
changesSinceBatchCommit={batchId}
>
{(shapes, fields) => (
<div className={classes.bodyDetails}>
<div>
{process.env.REACT_APP_FF_FIELD_LEVEL_EDITS !==
'true' ? (
<ContributionsList
renderField={(field) => (
<FieldOrParameter
key={
field.contribution.id +
field.contribution.contributionKey
}
name={field.name}
shapes={field.shapes}
depth={field.depth}
value={field.contribution.value}
required={field.required}
/>
)}
fieldDetails={fields}
/>
) : (
<FieldViewer fields={fields} />
)}
</div>
<div className={classes.panel}>
<HttpBodyPanel
shapes={shapes}
location={request.body!.contentType}
/>
</div>
</div>
)}
</ShapeFetcher>
) : (
<>No Body Request</>
)}
</>
)}
</HttpBodySelector>
</div>
)}
{selectors
.getResponsesInSortedOrder(visibleResponsesByStatusCode)
.map(([statusCode, responses]) => (
<div
className={classes.bodyContainer}
id={statusCode}
key={statusCode}
>
<div className={classes.bodyHeaderContainer}>
<h6 className={classes.bodyHeader}>{statusCode} Response</h6>
</div>
<HttpBodySelector
items={responses}
getDisplayName={(response) =>
response.body?.contentType || 'No Body'
}
>
{(response) => (
<>
<div className={classes.bodyContributionContainer}>
<ReactMarkdown
className={classes.contents}
source={response.description}
/>
</div>
<div className={classes.bodyDetails}>
{response.body ? (
<ShapeFetcher
rootShapeId={response.body.rootShapeId}
endpointId={endpointId}
changesSinceBatchCommit={batchId}
>
{(shapes, fields) => (
<>
<div>
{process.env.REACT_APP_FF_FIELD_LEVEL_EDITS !==
'true' ? (
<ContributionsList
renderField={(field) => (
<FieldOrParameter
key={
field.contribution.id +
field.contribution.contributionKey
}
name={field.name}
shapes={field.shapes}
depth={field.depth}
value={field.contribution.value}
required={field.required}
/>
)}
fieldDetails={fields}
/>
) : (
<FieldViewer fields={fields} />
)}
</div>
<div className={classes.panel}>
<HttpBodyPanel
shapes={shapes}
location={response.body!.contentType}
/>
</div>
</>
)}
</ShapeFetcher>
) : (
<>No Body Response</>
)}
</div>
</>
)}
</HttpBodySelector>
</div>
))}
</FullWidth>
</>
);
};
const useStyles = makeStyles((theme) => ({
regularField: {
fontSize: '1.25rem',
fontFamily: 'Ubuntu, Inter',
fontWeight: 500,
lineHeight: 1.6,
},
contents: {
fontSize: 16,
lineHeight: 1.6,
color: '#4f566b',
paddingRight: 50,
},
removedInfoHeader: {
justifyContent: 'center',
display: 'fixed',
},
bodyContainer: {
marginTop: theme.spacing(6),
width: '100%',
height: '100%',
},
bodyHeaderContainer: {},
bodyContributionContainer: {
marginBottom: theme.spacing(2),
},
bodyHeader: {
fontSize: '1.25rem',
fontFamily: FontFamily,
fontWeight: 500,
lineHeight: 1.6,
letterSpacing: '0.0075em',
margin: theme.spacing(3, 0),
},
bodyDetails: {
display: 'flex',
width: '100%',
height: '100%',
'& > div': {
width: '50%',
padding: theme.spacing(0, 1),
},
},
panel: {
position: 'sticky',
top: 50,
alignSelf: 'flex-start',
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/Interfaces.ts
|
<gh_stars>100-1000
import { IOpticEngine } from '@useoptic/spectacle';
import {
CQRSCommand,
IHttpInteraction,
ICoreShapeKinds,
} from '@useoptic/optic-domain';
import { ICopy } from '<src>/pages/diffs/components/ICopyRender';
import { IJsonTrail } from '../../../cli-shared/build/diffs/json-trail';
import { DomainIdGenerator } from './domain-id-generator';
import { DiffLocation } from './parse-diff';
import { IEndpoint } from '<src>/types';
export interface IInterpretation {
previewTabs: IInteractionPreviewTab[];
diffDescription: IDiffDescription;
updateSpecChoices: IPatchChoices;
toCommands: (choices: IPatchChoices) => CQRSCommand[];
}
export interface IShapeUpdateChoice {
coreShapeKind: ICoreShapeKinds;
isValid: boolean;
}
export interface IPatchChoices {
copy: ICopy[];
shapes: IShapeUpdateChoice[];
isOptional?: boolean;
shouldRemoveField?: boolean;
isField?: boolean;
isQueryParam?: boolean;
isShape?: boolean;
includeNewBody?: boolean;
isNewRegionDiff?: boolean;
}
export interface IInteractionPreviewTab {
title: string;
invalid: boolean;
assertion: ICopy[];
jsonTrailsByInteractions: { [key: string]: IJsonTrail[] };
interactionPointers: string[];
}
export interface BodyPreview {
asJson: any | null;
asText: any | null;
noBody: boolean;
empty: boolean;
}
export interface IDiffDescription {
title: ICopy[];
assertion: ICopy[];
location: DiffLocation;
changeType: IChangeType;
getJsonBodyToPreview: (interaction: IHttpInteraction) => BodyPreview;
unknownDiffBehavior?: boolean;
diffHash: string;
}
export interface ISuggestion {
action: ICopyPair;
commands: CQRSCommand[];
changeType: IChangeType;
}
export enum IChangeType {
Added,
Changed,
Removed,
}
interface ICopyPair {
activeTense: ICopy[];
pastTense: ICopy[];
}
export interface ISuggestion {
action: ICopyPair;
commands: CQRSCommand[];
changeType: IChangeType;
}
// Diff Types the UI Handles
// TODO QPB either remove this or handle this in a parsing function - this just means we have to update multiple places
export const allowedDiffTypes: {
[key: string]: {
isBodyShapeDiff: boolean;
inQuery: boolean;
inRequest: boolean;
inResponse: boolean;
unmatchedUrl: boolean;
asString: string;
};
} = {
UnmatchedRequestUrl: {
isBodyShapeDiff: false,
inQuery: false,
inRequest: false,
inResponse: false,
unmatchedUrl: true,
asString: 'UnmatchedRequestUrl',
},
UnmatchedRequestMethod: {
isBodyShapeDiff: false,
inQuery: false,
inRequest: false,
inResponse: false,
unmatchedUrl: true,
asString: 'UnmatchedRequestMethod',
},
UnmatchedQueryParameters: {
isBodyShapeDiff: false,
inQuery: true,
inRequest: false,
inResponse: false,
unmatchedUrl: false,
asString: 'UnmatchedQueryParameters',
},
UnmatchedRequestBodyContentType: {
isBodyShapeDiff: false,
inQuery: false,
inRequest: true,
inResponse: false,
unmatchedUrl: false,
asString: 'UnmatchedRequestBodyContentType',
},
UnmatchedResponseBodyContentType: {
isBodyShapeDiff: false,
inQuery: false,
inRequest: false,
inResponse: true,
unmatchedUrl: false,
asString: 'UnmatchedResponseBodyContentType',
},
UnmatchedResponseStatusCode: {
isBodyShapeDiff: false,
inQuery: false,
inRequest: false,
inResponse: true,
unmatchedUrl: false,
asString: 'UnmatchedResponseStatusCode',
},
UnmatchedQueryParametersShape: {
isBodyShapeDiff: true,
inQuery: true,
inRequest: false,
inResponse: false,
unmatchedUrl: false,
asString: 'UnmatchedQueryParametersShape',
},
UnmatchedRequestBodyShape: {
isBodyShapeDiff: true,
inQuery: false,
inRequest: true,
inResponse: false,
unmatchedUrl: false,
asString: 'UnmatchedRequestBodyShape',
},
UnmatchedResponseBodyShape: {
isBodyShapeDiff: true,
inQuery: false,
inRequest: false,
inResponse: true,
unmatchedUrl: false,
asString: 'UnmatchedResponseBodyShape',
},
};
export const allowedDiffTypesKeys: string[] = Object.keys(allowedDiffTypes);
// Properties of Each Diff Types
export const isBodyShapeDiff = (key: string): boolean =>
allowedDiffTypes[key]?.isBodyShapeDiff;
export const isDiffForKnownEndpoint = (key: string): boolean =>
!allowedDiffTypes[key]?.unmatchedUrl;
///////////////////////////////////////
export type CurrentSpecContext = {
currentSpecPaths: any[];
currentSpecEndpoints: IEndpoint[];
domainIds: DomainIdGenerator;
idGeneratorStrategy: 'sequential' | 'random';
opticEngine: IOpticEngine;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/domain-id-generator.ts
|
<filename>workspaces/ui-v2/src/lib/domain-id-generator.ts
// function newShapeId
// function newPathId
// function newRequestId
// function newResponseId
// function newRequestParameterId
// function newShapeParameterId
// function newFieldId
import shortId from 'shortid';
export interface DomainIdGenerator {
newShapeId: () => string;
newPathId: () => string;
newRequestId: () => string;
newResponseId: () => string;
newShapeParameterId: () => string;
newFieldId: () => string;
}
export function newDeterministicIdGenerator(): DomainIdGenerator {
const newShapeId = sequentialId('shape');
const newPathId = sequentialId('path');
const newRequestId = sequentialId('request');
const newResponseId = sequentialId('response');
const newShapeParameterId = sequentialId('shape-parameter');
const newFieldId = sequentialId('field');
return {
newShapeId,
newPathId,
newRequestId,
newResponseId,
newShapeParameterId,
newFieldId,
};
}
export function newRandomIdGenerator(): DomainIdGenerator {
const newShapeId = randomId('shape');
const newPathId = randomId('path');
const newRequestId = randomId('request');
const newResponseId = randomId('response');
const newShapeParameterId = randomId('shape-parameter');
const newFieldId = randomId('field');
return {
newShapeId,
newPathId,
newRequestId,
newResponseId,
newShapeParameterId,
newFieldId,
};
}
function sequentialId(prefix: string) {
let number = 0;
return () => {
const id = `${prefix}_${number}`;
number = number + 1;
return id;
};
}
function randomId(prefix: string) {
return () => {
return `${prefix}_${shortId.generate()}`;
};
}
|
tony-aq/optic
|
workspaces/ui-v2/src/utils/__tests__/findLongestCommonPath.test.ts
|
import { findLongestCommonPath } from '../findLongestCommonPath';
describe('findLongestCommonPath', () => {
test('returns the shared start for a list of items', () => {
const endpointNames = ['/api/list', '/api/:apiId', '/api/todos'].map((s) =>
s.split('/')
);
expect(findLongestCommonPath(endpointNames)).toBe('/api');
});
test('returns the shared start with same letters following slash', () => {
const endpointNames = ['/api/list', '/api/liststs'].map((s) =>
s.split('/')
);
expect(findLongestCommonPath(endpointNames)).toBe('/api');
});
test('returns the shared start for a single item', () => {
const endpointNames = ['/api/list'].map((s) => s.split('/'));
expect(findLongestCommonPath(endpointNames)).toBe('/api/list');
});
test('returns / for empty list', () => {
expect(findLongestCommonPath([])).toBe('/');
});
});
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/components/SimulatedBodyPreview.tsx
|
<gh_stars>100-1000
import React, { useEffect, useMemo, useState } from 'react';
import { CQRSCommand, JsonType } from '@useoptic/optic-domain';
import { ShapeFetcher, SimulatedCommandStore } from '<src>/components';
import { useSpectacleContext } from '<src>/contexts/spectacle-provider';
import { useAppSelector } from '<src>/store';
import { IShapeRenderer } from '<src>/types';
import { SpectacleClient } from '<src>/clients';
type SimulatedBodyProps = {
rootShapeId: string;
endpointId: string;
children: (shapes: IShapeRenderer[]) => React.ReactElement;
};
export const SimulatedBody = ({
rootShapeId,
endpointId,
children,
}: SimulatedBodyProps) => {
const spectacle = useSpectacleContext();
const spectacleClient = useMemo(() => new SpectacleClient(spectacle), [
spectacle,
]);
const [previewCommands, setPreviewCommands] = useState<CQRSCommand[]>([]);
// Commands that generate commands - removed fields
const fieldEdits = useAppSelector((state) => state.documentationEdits.fields);
useEffect(() => {
let isStale = false;
(async () => {
const { removed: removedFields, edited: editedFields } = fieldEdits;
const editFieldCommandsPromise: Promise<CQRSCommand[]> = Promise.all(
Object.entries(editedFields).map(([fieldId, options]) => {
const requestedTypes: JsonType[] = [];
if (options.isNullable) {
requestedTypes.push(JsonType.NULL);
}
if (options.isOptional) {
requestedTypes.push(JsonType.UNDEFINED);
}
return spectacleClient.fetchFieldEditCommands(
fieldId,
requestedTypes
);
})
).then((fieldCommands) => fieldCommands.flat());
const removeFieldCommandsPromise: Promise<CQRSCommand[]> = Promise.all(
removedFields.map((fieldId) =>
spectacleClient.fetchFieldRemoveCommands(fieldId)
)
).then((fieldCommands) => fieldCommands.flat());
const [editFieldCommands, removeFieldCommands] = await Promise.all([
editFieldCommandsPromise,
removeFieldCommandsPromise,
]);
if (!isStale) {
setPreviewCommands([...editFieldCommands, ...removeFieldCommands]);
}
})();
return () => {
isStale = true;
};
}, [fieldEdits, spectacleClient]);
return (
<SimulatedCommandStore
spectacle={spectacle}
previewCommands={previewCommands}
>
{(batchCommitId) => (
<ShapeFetcher
rootShapeId={rootShapeId}
endpointId={endpointId}
changesSinceBatchCommit={batchCommitId}
>
{children}
</ShapeFetcher>
)}
</SimulatedCommandStore>
);
};
|
tony-aq/optic
|
workspaces/cli-shared/src/diffs/interaction-trail.ts
|
//todo one time export from scala js, switch to types from Rust
export interface IInteractionTrail {
path: IInteractionTrailPathComponent[];
}
type IInteractionTrailPathComponent =
| IResponseHeaders
| IResponseBody
| IQueryString
| IUrl
| IRequestBody
| IRequestHeaders
| IMethod
| IResponseStatusCode;
interface IResponseHeaders {
ResponseHeaders: {
headerName: string;
};
}
interface IResponseBody {
ResponseBody: {
contentType: string;
statusCode: number;
};
}
interface IQueryString {
QueryString: {
queryString: string;
};
}
interface IUrl {
Url: {};
}
interface IRequestBody {
RequestBody: {
contentType: string;
};
}
interface IRequestHeaders {
RequestHeaders: {
headerName: string;
};
}
interface IMethod {
Method: {
method: string;
};
}
interface IResponseStatusCode {
ResponseStatusCode: {
statusCode: number;
};
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/shapes/slice.ts
|
import { createSlice, SerializedError } from '@reduxjs/toolkit';
import { AsyncStatus } from '<src>/types';
import { ShapeId, ReduxField, ReduxShape } from './types';
import { fetchShapes } from './thunks';
const initialState: {
rootShapes: Record<ShapeId, AsyncStatus<ShapeId, SerializedError>>;
shapeMap: Record<ShapeId, ReduxShape[]>;
fieldMap: Record<string, ReduxField>;
} = {
rootShapes: {},
shapeMap: {},
fieldMap: {},
};
const shapesSlice = createSlice({
name: 'shapes',
initialState,
reducers: {},
extraReducers: (builder) => {
// TODO we probably need to refetch shapes if they get outdated
builder.addCase(fetchShapes.pending, (state, action) => {
state.rootShapes[action.meta.arg.rootShapeId] = {
loading: true,
};
});
builder.addCase(fetchShapes.fulfilled, (state, action) => {
state.rootShapes[action.meta.arg.rootShapeId] = {
loading: false,
data: action.meta.arg.rootShapeId,
};
const { shapeMap, fieldMap } = action.payload;
for (const [shapeId, reduxShapes] of Object.entries(shapeMap)) {
state.shapeMap[shapeId] = reduxShapes;
}
state.fieldMap = {
...state.fieldMap,
...fieldMap,
};
});
builder.addCase(fetchShapes.rejected, (state, action) => {
state.rootShapes[action.meta.arg.rootShapeId] = {
loading: false,
error: action.error,
};
});
},
});
export const actions = {
fetchShapes,
};
export const reducer = shapesSlice.reducer;
|
tony-aq/optic
|
workspaces/optic-domain/src/streams/learning-results/index.ts
|
export * as UndocumentedEndpointBodies from './undocumented-endpoint-bodies';
export * as ShapeDiffAffordances from './shape-diff-affordances';
|
tony-aq/optic
|
workspaces/analytics/src/index.ts
|
<reponame>tony-aq/optic<filename>workspaces/analytics/src/index.ts
export * from './cliEvents';
export * from './eventbus';
export * from './uiEvents';
export * from './interfaces/TrackingEventBase';
|
tony-aq/optic
|
workspaces/ui-v2/src/store/diff/slice.ts
|
import { createSlice, SerializedError } from '@reduxjs/toolkit';
import { IAffordanceTrailsDiffHashMap } from '@useoptic/cli-shared/build/diffs/initial-types';
import { IUnrecognizedUrl } from '@useoptic/spectacle';
import { ParsedDiff } from '<src>/lib/parse-diff';
import { AsyncStatus } from '<src>/types';
import { fetchDiffsForCapture } from './thunks';
// This needs to be exported for typescript to be able to infer typings
export type DiffState = {
state: AsyncStatus<
{
diffs: ParsedDiff[];
urls: IUnrecognizedUrl[];
trails: IAffordanceTrailsDiffHashMap;
},
SerializedError
>;
// TODO - add in interactions, sharedDiffState data and pending endpoints
};
const initialState: DiffState = {
state: {
loading: true,
},
};
const diffSlice = createSlice({
name: 'diff',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchDiffsForCapture.pending, () => {
return initialState;
});
builder.addCase(fetchDiffsForCapture.fulfilled, (state, action) => {
state.state = {
loading: false,
data: action.payload.data,
};
});
builder.addCase(fetchDiffsForCapture.rejected, (state, action) => {
state.state = {
loading: false,
error: action.error,
};
});
},
});
export const actions = {
...diffSlice.actions,
fetchDiffsForCapture,
};
export const reducer = diffSlice.reducer;
|
tony-aq/optic
|
workspaces/ui-v2/src/store/endpoints/slice.ts
|
import { createSlice, SerializedError } from '@reduxjs/toolkit';
import { AsyncStatus, ChangeType, IEndpoint } from '<src>/types';
import { fetchEndpoints } from './thunks';
const initialState: {
results: AsyncStatus<
{
endpoints: IEndpoint[];
changes: Record<string, ChangeType>;
},
SerializedError
>;
} = {
results: {
loading: true,
},
};
const endpointsSlice = createSlice({
name: 'endpoints',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchEndpoints.pending, (state) => {
state.results = {
loading: true,
};
});
builder.addCase(fetchEndpoints.fulfilled, (state, action) => {
const results = action.payload;
state.results = {
loading: false,
data: results,
};
});
builder.addCase(fetchEndpoints.rejected, (state, action) => {
state.results = {
loading: false,
error: action.error,
};
});
},
});
export const actions = {
fetchEndpoints,
};
export const reducer = endpointsSlice.reducer;
|
tony-aq/optic
|
workspaces/cli-server/src/main.ts
|
import { CliDaemon } from './daemon';
import fs from 'fs-extra';
import { userDebugLogger } from '@useoptic/cli-shared';
import dotenv from 'dotenv';
import path from 'path';
import Config from './config';
import * as Errors from './errors';
if (process.env.OPTIC_DEBUG_ENV_FILE) {
console.log(`using overridden env ${process.env.OPTIC_DEBUG_ENV_FILE}`);
}
const envPath =
process.env.OPTIC_DEBUG_ENV_FILE || path.join(__dirname, '..', '.env');
dotenv.config({
path: envPath,
});
if (Config.errors.sentry) {
console.log('Sentry is enabled');
Errors.trackWithSentry(Config.errors.sentry);
console.log('Remote error tracking with Sentry enabled');
} else {
console.log('Sentry is disabled');
}
console.log('starting daemon', process.argv, process.env.DEBUG);
console.log(process.cwd(), __dirname, __filename);
const [, , lockFilePath, sentinelFilePath, cloudApiBaseUrl] = process.argv;
if (!lockFilePath) {
throw new Error(`missing lockFilePath`);
}
if (!sentinelFilePath) {
throw new Error(`missing sentinelFilePath`);
}
if (!cloudApiBaseUrl) {
throw new Error(`missing cloudApiBaseUrl`);
}
userDebugLogger(`daemon lock file ${lockFilePath}`);
const daemon = new CliDaemon({ lockFilePath, cloudApiBaseUrl });
daemon
.start()
.then(async (result) => {
userDebugLogger(`daemon started on port ${result.port}`);
await fs.writeJson(sentinelFilePath, result);
})
.catch((e) => {
console.error(e);
throw e;
});
|
tony-aq/optic
|
workspaces/local-cli/src/shared/ui-links.ts
|
export const linkToCapture = (
uiBaseUrl: string,
sessionId: string,
captureId: string
) => `${uiBaseUrl}/apis/${sessionId}/diffs/local/${captureId}`;
export const linkToDiffs = (uiBaseUrl: string, sessionId: string) =>
`${uiBaseUrl}/apis/${sessionId}/diffs`;
export const linkToDocumentation = (uiBaseUrl: string, sessionId: string) =>
`${uiBaseUrl}/apis/${sessionId}/documentation`;
export const linkToSetup = (sessionId: string) =>
`https://useoptic.com/document`;
|
tony-aq/optic
|
workspaces/ui-v2/src/entry-points/local/EnsureDaemonRunning.tsx
|
import React, { FC, useEffect, useState } from 'react';
import { makeStyles } from '@material-ui/core';
// import * as Sentry from '@sentry/react';
import { Client } from '@useoptic/cli-client';
import { FullPageLoader } from '<src>/components';
import * as SupportLinks from '<src>/constants/SupportLinks';
// const packageJson = require('../../../package.json');
// const uiPackageVersion = packageJson.version;
// TODO remove this and make sure the UI gets the latest side channel version attached when being built
// const trimPrereleaseVersions = (version: string): string =>
// version.split('-')[0];
export const EnsureDaemonRunning: FC = ({ children }) => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [hasMismatchedVersion] = useState(false);
useEffect(() => {
(async () => {
const cliClient = new Client('/api');
try {
await cliClient.daemonStatus();
// TODO - uncomment - there is currently an issue where chrome appears to aggressively cache
// package.json or some other file where there is version mismatches from the UI - even if
// the UI is correct - this is unvalidated and only from observations - not quite sure what's happening here
// if (
// trimPrereleaseVersions(version) !==
// trimPrereleaseVersions(uiPackageVersion)
// ) {
// Sentry.captureEvent({
// message: 'Mismatched UI and daemon versions',
// extra: {
// uiVersion: uiPackageVersion,
// daemonVersion: version,
// trimmedUiVersion: trimPrereleaseVersions(uiPackageVersion),
// trimmedDaemonVersion: trimPrereleaseVersions(version),
// },
// });
// setHasMismatchedVersions(true);
// }
setLoading(false);
} catch (e) {
setError(true);
setLoading(false);
}
})();
}, []);
return loading ? (
<FullPageLoader title="loading" />
) : hasMismatchedVersion ? (
<HasMismatchedVersionsError />
) : error ? (
<CliDaemonUnreachableError />
) : (
<>{children}</>
);
};
const HasMismatchedVersionsError: FC = () => {
const classes = useStyles();
return (
<div className={classes.errorContainer}>
<h2>Mismatched UI and daemon versions detected</h2>
<p>
It appears you are running mismatched versions of the UI and daemon.
</p>
<p>
This can happen when you have old daemon instances running in the
background when starting a new Optic session.
</p>
<p>
To fix this, you can run <code>api daemon:stop</code> and then rerun{' '}
<code>api spec</code> or <code>api start</code> to restart the server
</p>
<p>
If this continues to happen, please reach out to{' '}
<a
href={SupportLinks.Contact('Optic App has mismatched versions error')}
>
our team
</a>{' '}
for assistance. Further debug information can be found from our{' '}
<a href={SupportLinks.DebugLink} target="_blank" rel="noreferrer">
debugging instructions
</a>
.
</p>
</div>
);
};
const CliDaemonUnreachableError: FC = () => {
const classes = useStyles();
return (
<div className={classes.errorContainer}>
<h2>Error reaching daemon</h2>
<p>
It appears the cli daemon is unreachable. This usually means that the
daemon crashed and needs to be restarted.
</p>
<p>
You can restart the daemon by running <code>api spec</code> or
<code>api start</code>.
</p>
<p>
If this continues to happen, please reach out to{' '}
<a href={SupportLinks.Contact('Optic App cli daemon unreachable')}>
our team
</a>{' '}
for assistance. Further debug information can be found from our{' '}
<a href={SupportLinks.DebugLink} target="_blank" rel="noreferrer">
debugging instructions
</a>
.
</p>
</div>
);
};
const useStyles = makeStyles((theme) => ({
errorContainer: {
display: 'flex',
margin: 'auto',
flexDirection: 'column',
maxWidth: 1000,
width: '100%',
},
}));
|
tony-aq/optic
|
workspaces/local-cli/src/shared/analytics.ts
|
<reponame>tony-aq/optic
/*
Forwards events to the event bus running on cli-server
*/
import { IOpticTaskRunnerConfig } from '@useoptic/cli-config';
import { Client } from '@useoptic/cli-client';
import { TrackingEventBase } from '@useoptic/analytics/lib/interfaces/TrackingEventBase';
import { ensureDaemonStarted } from '@useoptic/cli-server';
import { lockFilePath } from './paths';
import { Config } from '../config';
export async function trackUserEvent({
apiName,
specId,
event,
}: {
apiName: string;
specId: string;
event: TrackingEventBase<any>;
}) {
const daemonState = await ensureDaemonStarted(
lockFilePath,
Config.apiBaseUrl
);
const cliServerClient = new Client(
`http://localhost:${daemonState.port}/api`
);
await cliServerClient.postTrackingEventsWithApi(apiName, [
{ ...event, data: { ...event.data, specId } },
]);
}
export function opticTaskToProps(
task: string,
config: IOpticTaskRunnerConfig
): any {
if (config) {
return {
task,
command: config.command,
'serviceConfig.port': config.serviceConfig.port,
'serviceConfig.host': config.serviceConfig.host,
'serviceConfig.protocol': config.serviceConfig.protocol,
'serviceConfig.basePath': config.serviceConfig.basePath,
'proxyConfig.port': config.proxyConfig.port,
'proxyConfig.host': config.proxyConfig.host,
'proxyConfig.protocol': config.proxyConfig.protocol,
'proxyConfig.basePath': config.proxyConfig.basePath,
};
} else {
return { task };
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/EndpointDocumentationPane.tsx
|
<gh_stars>100-1000
import React, { FC } from 'react';
import { makeStyles } from '@material-ui/core';
import {
EndpointName,
PathParameters,
FullWidth,
ShapeFetcher,
QueryParametersPanel,
HttpBodyPanel,
HttpBodySelector,
Panel,
} from '<src>/components';
import { EndpointTOC } from '<src>/pages/docs/components/EndpointTOC';
import { SubtleBlueBackground, FontFamily } from '<src>/styles';
import { DiffLocation } from '<src>/lib/parse-diff';
import {
HighlightedLocation,
Location,
} from '<src>/pages/diffs/components/HighlightedLocation';
import { selectors, useAppSelector } from '<src>/store';
import { getEndpointId } from '<src>/utils';
type EndpointDocumentationPaneProps = {
name: string;
method: string;
pathId: string;
lastBatchCommit?: string;
highlightBodyChanges?: boolean;
highlightedLocation?: DiffLocation;
};
export const EndpointDocumentationPane: FC<
EndpointDocumentationPaneProps & React.HtmlHTMLAttributes<HTMLDivElement>
> = ({
name,
method,
pathId,
lastBatchCommit,
highlightedLocation,
highlightBodyChanges,
...props
}) => {
const classes = useStyles();
const thisEndpoint = useAppSelector(
selectors.getEndpoint({ pathId, method })
);
const endpointChanges = useAppSelector(
(state) => state.endpoints.results.data?.changes || {}
);
const visibleQueryParameters =
thisEndpoint &&
thisEndpoint.query &&
selectors.isItemVisibleForChangelog(
thisEndpoint.query,
endpointChanges,
(query) => query.queryParametersId
)
? thisEndpoint.query
: null;
const visibleRequests = selectors.filterRemovedItemForChangelog(
thisEndpoint ? thisEndpoint.requests : [],
endpointChanges,
(request) => request.requestId
);
const visibleResponsesByStatusCode = selectors.filterMapOfRemovedItemsForChangelog(
thisEndpoint ? thisEndpoint.responsesByStatusCode : {},
endpointChanges,
(response) => response.responseId
);
if (!thisEndpoint) {
return <>no endpoint here</>;
}
const parameterizedPathParts = thisEndpoint.pathParameters.filter(
(path) => path.isParameterized
);
return (
<FullWidth
style={{ padding: 30, paddingTop: 15, paddingBottom: 400 }}
{...props}
>
<p className={classes.nameDisplay}>{name}</p>
<div style={{ height: 20 }} />
<Panel
header={
<EndpointName
fontSize={14}
leftPad={0}
method={thisEndpoint.method}
fullPath={thisEndpoint.fullPath}
/>
}
>
<PathParameters parameters={parameterizedPathParts} />
<div
style={{
marginTop: 10,
backgroundColor: SubtleBlueBackground,
borderTop: '1px solid #e2e2e2',
}}
>
<EndpointTOC
query={visibleQueryParameters}
requests={visibleRequests}
responsesByStatusCode={visibleResponsesByStatusCode}
/>
</div>
</Panel>
{visibleQueryParameters && (
<HighlightedLocation
className={classes.bodyContainer}
targetLocation={highlightedLocation}
expectedLocation={Location.Query}
>
<div id="query-parameters">
<h6 className={classes.bodyHeader}>Query Parameters</h6>
<div className={classes.bodyDetails}>
<ShapeFetcher
endpointId={getEndpointId(thisEndpoint)}
rootShapeId={visibleQueryParameters.rootShapeId}
changesSinceBatchCommit={lastBatchCommit}
>
{(shapes) => (
<QueryParametersPanel
parameters={selectors.convertShapeToQueryParameters(shapes)}
/>
)}
</ShapeFetcher>
</div>
</div>
</HighlightedLocation>
)}
{visibleRequests.length > 0 && (
<HighlightedLocation
className={classes.bodyContainer}
targetLocation={highlightedLocation}
expectedLocation={Location.Request}
>
<div id="request-body">
<h6 className={classes.bodyHeader}>Request Body</h6>
<div className={classes.bodyDetails}>
<HttpBodySelector
items={visibleRequests}
getDisplayName={(request) =>
request.body?.contentType || 'No Body'
}
>
{(request) =>
request.body ? (
<ShapeFetcher
endpointId={getEndpointId(thisEndpoint)}
rootShapeId={request.body.rootShapeId}
changesSinceBatchCommit={lastBatchCommit}
>
{(shapes) => (
<HttpBodyPanel
shapes={shapes}
// Typescript cannot infer through render props for some reason
location={`Request Body ${request.body!.contentType}`}
/>
)}
</ShapeFetcher>
) : (
<div>No Body Request</div>
)
}
</HttpBodySelector>
</div>
</div>
</HighlightedLocation>
)}
{selectors
.getResponsesInSortedOrder(visibleResponsesByStatusCode)
.map(([statusCode, responses]) => {
return (
<React.Fragment key={statusCode}>
<HighlightedLocation
className={classes.bodyContainer}
targetLocation={highlightedLocation}
statusCode={Number(statusCode)}
expectedLocation={Location.Response}
>
<div id={statusCode}>
<h6 className={classes.bodyHeader}>{statusCode} response</h6>
<div className={classes.bodyDetails}>
<HttpBodySelector
items={responses}
getDisplayName={(response) =>
response.body?.contentType || 'No Body'
}
>
{(response) =>
response.body ? (
<ShapeFetcher
endpointId={getEndpointId(thisEndpoint)}
rootShapeId={response.body.rootShapeId}
changesSinceBatchCommit={lastBatchCommit}
>
{(shapes) => (
<HttpBodyPanel
shapes={shapes}
location={`${response.statusCode} response ${
response.body!.contentType
}`}
/>
)}
</ShapeFetcher>
) : (
<div>No Body Request</div>
)
}
</HttpBodySelector>
</div>
</div>
</HighlightedLocation>
</React.Fragment>
);
})}
</FullWidth>
);
};
const useStyles = makeStyles((theme) => ({
bodyContainer: {
margin: theme.spacing(3, 0),
},
bodyHeader: {
fontSize: '1.25rem',
fontFamily: FontFamily,
fontWeight: 500,
lineHeight: 1.6,
letterSpacing: '0.0075em',
marginTop: 0,
marginBottom: theme.spacing(2),
},
bodyDetails: {
padding: theme.spacing(0, 1),
},
nameDisplay: {
fontSize: '1.25rem',
fontFamily: 'Ubuntu, Inter',
fontWeight: 500,
lineHeight: 1.6,
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/components/loaders/SpinningOpticLogo.tsx
|
import React from 'react';
import { makeStyles } from '@material-ui/styles';
export function SpinningOpticLogo() {
const classes = useStyles();
return (
<img
className={classes.spinningImg}
src={'/optic-logo-loader.svg'}
width={30}
height={30}
alt="loader"
/>
);
}
const useStyles = makeStyles((theme) => ({
spinningImg: {
animation: '$spin 5s infinite linear',
},
'@keyframes spin': {
'0%': { transform: 'rotate(0deg)' },
'100%': { transform: 'rotate(360deg)' },
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/DocumentationRootPage/DocumentationRootPage.tsx
|
<filename>workspaces/ui-v2/src/pages/docs/DocumentationRootPage/DocumentationRootPage.tsx
import React, { FC, useEffect } from 'react';
import { Box, List, LinearProgress, Typography } from '@material-ui/core';
import { CenteredColumn, PageLayout } from '<src>/components';
import {
useAppSelector,
useAppDispatch,
documentationEditActions,
selectors,
} from '<src>/store';
import { useRunOnKeypress } from '<src>/hooks/util';
import { useGroupedEndpoints } from '<src>/hooks/useGroupedEndpoints';
import { IEndpoint } from '<src>/types';
import { DocsPageAccessoryNavigation } from '../components';
import { EndpointRow } from './EndpointRow';
import { useAnalytics } from '<src>/contexts/analytics';
export const DocumentationRootPageWithDocsNav: FC = () => (
<PageLayout AccessoryNavigation={DocsPageAccessoryNavigation}>
<DocumentationRootPage />
</PageLayout>
);
export function DocumentationRootPage() {
const analytics = useAnalytics();
const endpointsState = useAppSelector((state) => state.endpoints.results);
const isEditing = useAppSelector(
(state) => state.documentationEdits.isEditing
);
const pendingCount = useAppSelector(
selectors.getDocumentationEditStagedCount
);
const dispatch = useAppDispatch();
const setCommitModalOpen = (commitModalOpen: boolean) => {
dispatch(
documentationEditActions.updateCommitModalState({
commitModalOpen,
})
);
};
const filteredEndpoints = selectors.filterRemovedItems(
endpointsState.data?.endpoints || []
);
const groupedEndpoints = useGroupedEndpoints(filteredEndpoints);
useEffect(() => {
analytics.documentationPageLoaded();
}, [analytics]);
const tocKeys = Object.keys(groupedEndpoints).sort();
const onKeyPress = useRunOnKeypress(
() => {
if (isEditing && pendingCount > 0) {
setCommitModalOpen(true);
}
},
{
keys: new Set(['Enter']),
inputTagNames: new Set(['input']),
}
);
if (endpointsState.loading) {
return <LinearProgress variant="indeterminate" />;
}
if (tocKeys.length === 0) {
return (
<Box
display="flex"
height="100%"
alignItems="center"
justifyContent="center"
>
<Typography
variant="h6"
style={{ fontFamily: 'Ubuntu Mono', marginBottom: '25%' }}
>
No endpoints have been documented yet
</Typography>
</Box>
);
}
return (
<CenteredColumn maxWidth="md" style={{ marginTop: 35 }}>
<List dense onKeyPress={onKeyPress}>
{tocKeys.map((tocKey) => {
return (
<div key={tocKey}>
<Typography
variant="h6"
style={{ fontFamily: 'Ubuntu Mono', fontWeight: 600 }}
>
{tocKey}
</Typography>
{groupedEndpoints[tocKey].map((endpoint: IEndpoint) => (
<EndpointRow
endpoint={endpoint}
key={endpoint.pathId + endpoint.method}
/>
))}
</div>
);
})}
</List>
</CenteredColumn>
);
}
|
tony-aq/optic
|
workspaces/snapshot-tests/src/regressions/index.ts
|
import * as fs from 'fs-extra';
import * as Path from 'path';
import {
LocalCliCapturesService,
LocalCliSpectacle,
} from '@useoptic/spectacle-shared';
import * as opticEngine from '@useoptic/optic-engine-wasm';
async function main(input: {
interactionsCount: string;
outputBaseDirectory: string;
baseDirectory: string;
}) {
const apiId = '1';
const captureId = 'ccc';
const apiBaseUrl = 'http://localhost:34444';
const baseUrl = `${apiBaseUrl}/api/specs/${apiId}`;
const spectacle = new LocalCliSpectacle(baseUrl, opticEngine);
const capturesService = new LocalCliCapturesService({ spectacle, baseUrl });
const diffId = 'ddd';
console.log('diffing');
const diff = await capturesService.startDiff(diffId, captureId);
const diffService = await diff.onComplete;
const [
listDiffsResult,
learnShapeDiffAffordancesResult,
listUnrecognizedUrlsResult,
] = await Promise.all([
diffService.listDiffs(),
diffService.learnShapeDiffAffordances(),
diffService.listUnrecognizedUrls(),
]);
const outputDir = input.outputBaseDirectory;
await fs.ensureDir(outputDir);
await fs.emptyDir(outputDir);
await Promise.all([
fs.writeJson(
Path.join(outputDir, 'listDiffsResult.json'),
listDiffsResult,
{ spaces: 2 }
),
fs.writeJson(
Path.join(outputDir, 'learnShapeDiffAffordancesResult.json'),
learnShapeDiffAffordancesResult,
{ spaces: 2 }
),
fs.writeJson(
Path.join(outputDir, 'listUnrecognizedUrlsResult.json'),
listUnrecognizedUrlsResult,
{ spaces: 2 }
),
]);
}
const [
,
,
outputBaseDirectory,
baseDirectory,
interactionsCount,
] = process.argv;
main({ baseDirectory, outputBaseDirectory, interactionsCount })
.then(() => {
console.log('Done!');
})
.catch((e) => {
console.error(e);
});
|
tony-aq/optic
|
workspaces/cli-config/src/opticrc/optic-rc.ts
|
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
import { hri } from 'human-readable-ids';
export const opticrcPath = path.resolve(os.homedir(), '.opticrc');
const getSourceFromEnv = () => process.env.__OPTIC_SOURCE || 'user';
export function defaultStorage(): IUserStorage {
return {
anonymousId: hri.random(),
source: getSourceFromEnv(),
};
}
export interface IUserStorage {
idToken?: string;
anonymousId: string;
source: string;
}
export async function getCurrentStorage(): Promise<IUserStorage | undefined> {
try {
const storage: IUserStorage = await fs.readJSON(opticrcPath);
return storage;
} catch (e) {
return undefined;
}
}
async function getOrCreateKey<T extends keyof IUserStorage>(
key: T,
defaultValue: () => IUserStorage[T]
): Promise<IUserStorage[T]> {
const storage = await getCurrentStorage();
if (storage && storage[key]) {
return storage[key];
} else if (storage) {
const storeValue = {
...storage,
[key]: defaultValue(),
};
await fs.ensureFile(opticrcPath);
await fs.writeFile(opticrcPath, JSON.stringify(storeValue));
return storage[key];
} else {
const storeValue = {
...defaultStorage(),
[key]: defaultValue(),
};
await fs.ensureFile(opticrcPath);
await fs.writeFile(opticrcPath, JSON.stringify(storeValue));
return storeValue[key];
}
}
export function getOrCreateAnonId(): Promise<string> {
return getOrCreateKey('anonymousId', hri.random);
}
export function getOrCreateSource(): Promise<string> {
return getOrCreateKey('source', getSourceFromEnv);
}
|
tony-aq/optic
|
workspaces/optic-domain/src/streams/learning-results/shape-diff-affordances.ts
|
<reponame>tony-aq/optic<filename>workspaces/optic-domain/src/streams/learning-results/shape-diff-affordances.ts
import { Readable } from 'stream';
import { fromReadableJSONL, lastBy, reduce } from '../../async-tools';
export interface ShapeDiffAffordances {
affordances: any[];
interactions: any[];
}
export type DiffFingerprint = string;
export type ShapeDiffAffordancesResult = [
ShapeDiffAffordances,
DiffFingerprint
];
export function fromJSONL(): (
source: Readable
) => AsyncIterable<ShapeDiffAffordancesResult> {
return fromReadableJSONL();
}
// yield each last unique diff result (using fingerprint as identity)
export const lastUnique = lastBy(
([_affordances, fingerprint]: ShapeDiffAffordancesResult) => fingerprint
);
export function affordancesByFingerprint(): (
source: AsyncIterable<ShapeDiffAffordancesResult>
) => Promise<{ [fingerprint: string]: ShapeDiffAffordances }> {
return reduce(
(
affordancesByFingerprint: { [fingerprint: string]: ShapeDiffAffordances },
[affordance, fingerprint]
) => {
affordancesByFingerprint[fingerprint] = affordance;
return affordancesByFingerprint;
},
{}
);
}
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/__tests/diff-helpers/universes/makeCurrentSpecContext.ts
|
import { CurrentSpecContext } from '<src>/lib/Interfaces';
import {
AllEndpointsQuery,
endpointQueryResultsToJson,
EndpointQueryResults,
} from '<src>/store/endpoints/thunks';
import { IBaseSpectacle } from '@useoptic/spectacle';
import { newDeterministicIdGenerator } from '<src>/lib/domain-id-generator';
import * as opticEngine from '@useoptic/optic-engine-wasm';
import { AllPathsQuery, PathQueryResponse } from '<src>/store/paths/thunks';
//@GOTCHA: for some reason, probably because of jest, our wasm code thinks it is running in the browser even though it is running in node because of the presence of global.self:
//@REF: https://github.com/rust-random/getrandom/issues/214
//@ts-ignore
delete global.self;
export async function makeCurrentSpecContext(
events: any[],
query: IBaseSpectacle['query']
): Promise<CurrentSpecContext> {
const { endpoints } = endpointQueryResultsToJson(
(
await query<EndpointQueryResults>({
query: AllEndpointsQuery,
variables: {},
})
).data || {
endpoints: [],
},
null,
false
);
const { paths } = (
await query<PathQueryResponse>({
query: AllPathsQuery,
variables: {},
})
).data || { paths: [] };
return {
currentSpecPaths: paths,
currentSpecEndpoints: endpoints,
domainIds: newDeterministicIdGenerator(),
idGeneratorStrategy: 'sequential',
opticEngine,
};
}
|
tony-aq/optic
|
workspaces/ui-v2/src/entry-points/local/local-cli.tsx
|
import * as React from 'react';
import { useEffect, useState, useMemo, useRef } from 'react';
import {
useRouteMatch,
useParams,
Route,
Redirect,
Switch,
} from 'react-router-dom';
import { LinearProgress } from '@material-ui/core';
import { AsyncStatus } from '<src>/types';
import { Provider as ReduxProvider } from 'react-redux';
import { Provider as BaseUrlProvider } from '<src>/hooks/useBaseUrl';
import { DocumentationPages } from '<src>/pages/docs';
import { SpectacleStore } from '<src>/contexts/spectacle-provider';
import { DiffReviewEnvironments } from '<src>/pages/diffs/ReviewDiffPages';
import { CapturesServiceStore } from '<src>/hooks/useCapturesHook';
import { ChangelogPages } from '<src>/pages/changelog/ChangelogPages';
import { ChangelogHistory } from '<src>/pages/changelogHistory';
import { DebugOpticComponent } from '<src>/components';
import {
AppConfigurationStore,
OpticAppConfig,
} from '<src>/contexts/config/AppConfiguration';
import { ConfigRepositoryStore } from '<src>/contexts/OpticConfigContext';
import { useOpticEngine } from '<src>/hooks/useOpticEngine';
import {
LocalCliCapturesService,
LocalCliConfigRepository,
LocalCliServices,
LocalCliSpectacle,
UILocalCliSpecRepository,
} from '@useoptic/spectacle-shared';
import { AnalyticsStore } from '<src>/contexts/analytics';
import {
getMetadata,
initialize,
track,
} from '<src>/contexts/analytics/implementations/localCliAnalytics';
import { store } from '<src>/store';
import { MetadataLoader } from '<src>/contexts/MetadataLoader';
import { Auth0Provider } from '@auth0/auth0-react';
import { SpecRepositoryStore } from '<src>/contexts/SpecRepositoryContext';
import { EnsureDaemonRunning } from './EnsureDaemonRunning';
const appConfig: OpticAppConfig = {
config: {
allowEditing: true,
analytics: {
enabled: Boolean(process.env.REACT_APP_ENABLE_ANALYTICS === 'yes'),
segmentToken: process.env.REACT_APP_SEGMENT_LOCAL_UI,
fullStoryOrgId: process.env.REACT_APP_FULLSTORY_ORG,
sentryUrl: process.env.REACT_APP_SENTRY_URL,
intercomAppId: process.env.REACT_APP_INTERCOM_APP_ID,
},
backendApi: {
domain: process.env.REACT_APP_BACKEND_API_BASE || '',
},
sharing: {
enabled: true,
specViewerDomain: process.env.REACT_APP_SPEC_VIEWER_BASE || '',
},
},
};
const AUTH0_DOMAIN = process.env.REACT_APP_AUTH0_DOMAIN || 'optic.auth0.com';
const AUTH0_CLIENT_ID =
process.env.REACT_APP_AUTH0_CLIENT_ID || 'S7AeH5IQweLb2KHNoyfQfKBtkroE1joF';
export default function LocalCli() {
const match = useRouteMatch();
const params = useParams<{ specId: string }>();
const { specId } = params;
const { loading, error, data } = useLocalCliServices(specId);
if (loading) {
return <LinearProgress variant="indeterminate" />;
}
if (error) {
return <div>error :(</div>;
}
if (!data) {
return <div>something went wrong</div>;
}
return (
<AppConfigurationStore config={appConfig}>
<SpectacleStore spectacle={data.spectacle}>
<ConfigRepositoryStore config={data.configRepository}>
<CapturesServiceStore capturesService={data.capturesService}>
<ReduxProvider store={store}>
<SpecRepositoryStore specRepo={data.specRepository}>
<BaseUrlProvider value={{ url: match.url }}>
<Auth0Provider
domain={AUTH0_DOMAIN}
clientId={AUTH0_CLIENT_ID}
audience={appConfig.config.backendApi.domain}
>
<EnsureDaemonRunning>
<MetadataLoader>
<AnalyticsStore
getMetadata={getMetadata(() =>
data.configRepository.getApiName()
)}
initialize={initialize}
track={track}
>
<DebugOpticComponent />
<Switch>
<Route
path={`${match.path}/history`}
component={ChangelogHistory}
/>
<Route
path={`${match.path}/changes-since/:batchId`}
component={ChangelogPages}
/>
<Route
path={`${match.path}/documentation`}
component={DocumentationPages}
/>
<Route
path={`${match.path}/diffs`}
component={DiffReviewEnvironments}
/>
<Redirect to={`${match.path}/documentation`} />
</Switch>
</AnalyticsStore>
</MetadataLoader>
</EnsureDaemonRunning>
</Auth0Provider>
</BaseUrlProvider>
</SpecRepositoryStore>
</ReduxProvider>
</CapturesServiceStore>
</ConfigRepositoryStore>
</SpectacleStore>
</AppConfigurationStore>
);
}
export function useLocalCliServices(
specId: string
): AsyncStatus<LocalCliServices> {
const opticEngine = useOpticEngine();
const apiBaseUrl = `/api/specs/${specId}`;
const [spectacle, setSpectacle] = useState(
new LocalCliSpectacle(apiBaseUrl, opticEngine)
);
const refEngine = useRef(opticEngine);
const refApiUrl = useRef(apiBaseUrl);
useEffect(() => {
const refreshFn = () => {
setSpectacle(new LocalCliSpectacle(refApiUrl.current, refEngine.current));
};
spectacle.registerUpdateEvent(refreshFn);
return () => spectacle.unregisterUpdateEvent(refreshFn);
}, [spectacle]);
const capturesService = useMemo(
() =>
new LocalCliCapturesService({
baseUrl: apiBaseUrl,
spectacle,
}),
[apiBaseUrl, spectacle]
);
const configRepository = new LocalCliConfigRepository({
baseUrl: apiBaseUrl,
spectacle,
});
const specRepository = new UILocalCliSpecRepository({ baseUrl: apiBaseUrl });
return {
loading: false,
data: {
spectacle,
capturesService,
opticEngine,
configRepository,
specRepository,
},
};
}
|
tony-aq/optic
|
workspaces/ui-v2/src/contexts/analytics/AnalyticsStore.tsx
|
<reponame>tony-aq/optic
import React, { FC, useContext, useEffect, useRef, useState } from 'react';
import { OpticUIEvents, TrackingEventBase } from '@useoptic/analytics';
import { InvariantViolationError } from '<src>/errors';
import { useAppConfig } from '../config/AppConfiguration';
import { useAppSelector } from '<src>/store';
const packageJson = require('../../../package.json');
const clientId = `local_cli_${packageJson.version}`;
const AnalyticsContext = React.createContext<
| {
trackEvent: OpticUIEvents;
}
| undefined
>(undefined);
type AnalyticsMetadata = {
clientId: string;
clientAgent: string;
apiName: string;
specId: string;
};
type InputAnalyticsMetadata = Omit<AnalyticsMetadata, 'specId'>;
const defaultMetadata: InputAnalyticsMetadata = {
clientId,
clientAgent: 'anon_id',
apiName: '',
};
export type AnalyticsStoreProps = {
getMetadata: () => Promise<InputAnalyticsMetadata>;
initialize: (
metadata: InputAnalyticsMetadata,
appConfig: ReturnType<typeof useAppConfig>
) => Promise<void>;
track: (
event: TrackingEventBase<any>,
metadata: AnalyticsMetadata
) => Promise<void>;
};
export const AnalyticsStore: FC<AnalyticsStoreProps> = ({
children,
getMetadata,
initialize,
track,
}) => {
const appConfig = useAppConfig();
const refGetMetadata = useRef(getMetadata);
const refInitialize = useRef(initialize);
const refTrack = useRef(track);
const [metadata, setMetadata] = useState<InputAnalyticsMetadata>(
defaultMetadata
);
const specId = useAppSelector(
(state) => state.metadata.data?.specificationId!
);
const cfgRef = useRef({
metadata,
specId,
});
useEffect(() => {
cfgRef.current.metadata = metadata;
cfgRef.current.specId = specId;
}, [metadata, specId, cfgRef]);
useEffect(() => {
(async function () {
if (appConfig.analytics.enabled) {
const fetchedMetadata = await refGetMetadata.current();
setMetadata(fetchedMetadata);
refInitialize.current(fetchedMetadata, appConfig);
}
})();
}, [appConfig]);
const opticUITrackingEvents = useRef(
new OpticUIEvents(async (event: any) => {
if (appConfig.analytics.enabled) {
refTrack.current(event, {
...cfgRef.current.metadata,
specId: cfgRef.current.specId ?? 'anon-spec-id',
});
}
})
);
return (
<AnalyticsContext.Provider
value={{ trackEvent: opticUITrackingEvents.current }}
>
{children}
</AnalyticsContext.Provider>
);
};
export function useAnalytics(): OpticUIEvents {
const value = useContext(AnalyticsContext);
if (!value) {
throw new InvariantViolationError(
'useAnalytics could not find AnalyticsContext'
);
}
return value.trackEvent;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/FieldOrParameter.tsx
|
<filename>workspaces/ui-v2/src/components/FieldOrParameter.tsx
import React, { FC } from 'react';
import makeStyles from '@material-ui/styles/makeStyles';
import { IShapeRenderer } from '<src>/types';
import { EditableTextField, TextFieldVariant } from './EditableTextField';
export type FieldOrParameterProps = {
shapes: IShapeRenderer[];
name: string;
depth: number;
value: string;
setValue?: (newValue: string) => void;
isEditing?: boolean;
required: boolean;
};
export const FieldOrParameter: FC<
FieldOrParameterProps & React.HtmlHTMLAttributes<HTMLInputElement>
> = ({
name,
shapes,
depth,
value,
setValue = () => {},
isEditing = false,
required,
...props
}) => {
const classes = useStyles();
return (
<div className={classes.container} style={{ paddingLeft: depth * 14 }}>
<div className={classes.topRow}>
<div className={classes.keyName}>{name}</div>
<div className={classes.shape}>{summarizeTypes(shapes, required)}</div>
</div>
<EditableTextField
{...props}
isEditing={isEditing}
value={value}
setValue={setValue}
defaultText={`What is ${name}? How is it used?`}
variant={TextFieldVariant.FIELDORPARAM}
/>
</div>
);
};
function summarizeTypes(shapes: IShapeRenderer[], required: boolean) {
const optionalText = required ? '' : ' (optional)';
if (shapes.length === 1) {
return shapes[0].jsonType.toString().toLowerCase() + optionalText;
} else {
const allShapes = shapes.map((i) => i.jsonType.toString().toLowerCase());
const last = allShapes.pop();
return allShapes.join(', ') + ' or ' + last + optionalText;
}
}
const useStyles = makeStyles((theme) => ({
container: {
marginBottom: 9,
paddingLeft: 3,
borderTop: '1px solid #e4e8ed',
},
keyName: {
color: '#3c4257',
fontWeight: 600,
fontSize: 13,
fontFamily: 'Ubuntu',
},
shape: {
marginLeft: 6,
fontFamily: 'Ubuntu Mono',
fontSize: 12,
fontWeight: 400,
color: '#8792a2',
height: 18,
marginTop: 2,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
topRow: {
display: 'flex',
alignItems: 'center',
paddingTop: 9,
paddingBottom: 6,
},
}));
|
tony-aq/optic
|
workspaces/optic-domain/src/streams/diff-results.ts
|
<gh_stars>100-1000
import { lastBy } from '../async-tools';
import { fromReadableJSONL } from '../async-tools';
import { Readable } from 'stream';
// TODO: more strictly type the interaction diff result. Move them over from
// workspaces/cli-shared/diffs/diffs to optic-domain
export type DiffResult = [any, string[], string];
export function fromJSONL(): (source: Readable) => AsyncIterable<DiffResult> {
return fromReadableJSONL();
}
export async function* normalize(
diffResults: AsyncIterable<DiffResult>
): AsyncIterable<DiffResult> {
let pointersByFingerprint: Map<String, string[]> = new Map();
for await (let [diff, pointers, fingerprint] of diffResults) {
let existingPointers = pointersByFingerprint.get(fingerprint) || [];
let newPointers = [...existingPointers, ...pointers];
pointersByFingerprint.set(fingerprint, newPointers);
yield [diff, [...newPointers], fingerprint];
}
}
export { fromDiffResults as intoUndocumentedUrls } from './undocumented-urls';
// yield each last unique diff result (using fingerprint as identity)
export const lastUnique = lastBy(
([_diff, _tags, fingerprint]: DiffResult) => fingerprint
);
|
tony-aq/optic
|
workspaces/local-cli/src/commands/scripts.ts
|
<filename>workspaces/local-cli/src/commands/scripts.ts
import { Command, flags } from '@oclif/command';
// @ts-ignore
import {
getPathsRelativeToConfig,
IApiCliConfig,
IPathMapping,
readApiConfig,
} from '@useoptic/cli-config';
//@ts-ignore
import niceTry from 'nice-try';
import { cli } from 'cli-ux';
//@ts-ignore
import which from 'which';
import colors from 'colors';
import { IOpticScript } from '@useoptic/cli-config/build';
import {
developerDebugLogger,
fromOptic,
userDebugLogger,
} from '@useoptic/cli-shared';
import { generateOas } from './generate/oas';
import {
spawnProcess,
spawnProcessReturnExitCode,
} from '../shared/spawn-process';
import { ensureDaemonStarted } from '@useoptic/cli-server';
import { lockFilePath } from '../shared/paths';
import { Config } from '../config';
import { Client } from '@useoptic/cli-client';
export default class Scripts extends Command {
static description =
'run one of the scripts in optic.yml with the current specification';
static args = [
{
name: 'scriptName',
required: true,
},
];
static flags = {
install: flags.boolean({
required: false,
char: 'i',
}),
};
async run() {
const { args, flags } = this.parse(Scripts);
const scriptName: string = args.scriptName;
const script: IOpticScript | undefined = await niceTry(async () => {
const paths = await getPathsRelativeToConfig();
const config = await readApiConfig(paths.configPath);
const foundScript = config.scripts?.[scriptName!];
if (foundScript) {
return normalizeScript(foundScript);
} else {
cli.log(
fromOptic(
`Script ${colors.grey.bold(
scriptName
)} does not exist. Try one of these ${colors.grey.bold(
'api scripts <scriptname>'
)}`
)
);
return cli.log(
Object.keys(config.scripts || [])
.map((i) => '- ' + i)
.sort()
.join('\n')
);
}
});
if (scriptName && script) {
this.log(fromOptic(`Found Script ${colors.bold(scriptName)}`));
const { found, missing } = await checkDependencies(script);
if (missing.length) {
const hasInstallScript = Boolean(script.install);
this.log(
fromOptic(
colors.red(
`Some bin dependencies are missing ${JSON.stringify(missing)}. ${
hasInstallScript &&
!flags.install &&
"Run the command again with the flag '--install' to install them"
}`
)
)
);
if (hasInstallScript && flags.install) {
const result = await tryInstall(script.install!);
if (!result) {
return this.log(
fromOptic(
colors.red(
'Install command failed. Please install the dependencies for this script manually'
)
)
);
} else {
return this.executeScript(script);
}
}
return;
} else {
return this.executeScript(script);
}
} else {
this.log(
fromOptic(colors.red(`No script ${scriptName} found in optic.yml`))
);
}
}
async executeScript(script: IOpticScript) {
const oasPaths: any = await generateOas(true, true)!;
let { paths } = (await this.requiresSpec())!;
const daemonState = await ensureDaemonStarted(
lockFilePath,
Config.apiBaseUrl
);
const apiBaseUrl = `http://localhost:${daemonState.port}/api`;
const cliClient = new Client(apiBaseUrl);
const cliSession = await cliClient.findSession(paths.cwd, null, null);
const spectacleUrl = `${apiBaseUrl}/specs/${cliSession.session.id}/spectacle`;
const env: any = {
OPENAPI_JSON: oasPaths.json,
OPENAPI_YAML: oasPaths.yaml,
SPECTACLE_URL: spectacleUrl,
};
console.log(`Running command: ${colors.grey(script.command)} `);
const exitCode = await spawnProcessReturnExitCode(script.command, env);
process.exit(exitCode);
}
// TODO: this is copy/pasted from commands/status.ts
async requiresSpec(): Promise<
| {
paths: IPathMapping;
config: IApiCliConfig;
}
| undefined
> {
let paths: IPathMapping;
let config: IApiCliConfig;
try {
paths = await getPathsRelativeToConfig();
config = await readApiConfig(paths.configPath);
return { paths, config };
} catch (e) {
userDebugLogger(e);
await this.exitWithError(
`No optic.yml file found here. Add Optic to your API by running ${colors.bold(
'api init'
)}`
);
}
}
// TODO: this is copy/pasted from commands/status.ts
async exitWithError(error: string) {
this.log(fromOptic(error));
process.exit(0);
}
}
function normalizeScript(scriptRaw: string | IOpticScript): IOpticScript {
if (typeof scriptRaw === 'string') {
return {
command: scriptRaw,
dependsOn: [],
};
} else {
const dependsOn =
(scriptRaw.dependsOn && typeof scriptRaw.dependsOn === 'string'
? [scriptRaw.dependsOn]
: scriptRaw.dependsOn) || [];
return { ...scriptRaw, dependsOn };
}
}
async function checkDependencies(
script: IOpticScript
): Promise<{ found: string[]; missing: string[] }> {
const dependencies = script.dependsOn as Array<string>;
cli.action.start(
`${colors.bold(`Checking bin dependencies`)} ${colors.grey(
'Requiring ' + JSON.stringify(dependencies)
)}`
);
const results: [string, string][] = [];
for (const bin of dependencies) {
const pathToBin = which.sync(bin, { nothrow: true });
results.push([bin, pathToBin]);
}
const found = results.filter((i) => Boolean(i[1])).map((i) => i[0]);
const missing = results.filter((i) => !Boolean(i[1])).map((i) => i[0]);
if (missing.length === 0) {
cli.action.stop(colors.green.bold('✓ All dependencies found'));
} else {
cli.action.stop(colors.red('Missing dependencies'));
}
return { found, missing };
}
async function tryInstall(installScript: string): Promise<boolean> {
cli.action.start(`Running install command: ${colors.grey(installScript)} `);
const status = await spawnProcess(installScript);
cli.action.stop('Success!');
return status;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/shape-diffs/root.ts
|
<gh_stars>100-1000
import { BodyShapeDiff, DiffLocation } from '../parse-diff';
import { Actual, Expectation } from '../shape-diff-dsl-rust';
import {
CurrentSpecContext,
IDiffDescription,
IInteractionPreviewTab,
IInterpretation,
IPatchChoices,
} from '../Interfaces';
import sortBy from 'lodash.sortby';
import { code, plain } from '<src>/pages/diffs/components/ICopyRender';
import { builderInnerShapeFromChoices } from './build-inner-shape';
import {
SetRequestBodyShape,
SetResponseBodyShape,
ShapedBodyDescriptor,
SetQueryParametersShape,
QueryParametersShapeDescriptor,
CQRSCommand,
} from '@useoptic/optic-domain';
import { InvariantViolationError } from '<src>/errors';
export function rootShapeDiffInterpreter(
shapeDiff: BodyShapeDiff,
diffDescription: IDiffDescription,
actual: Actual,
expected: Expectation,
currentSpecContext: CurrentSpecContext
): IInterpretation {
const isUnmatched = shapeDiff.isUnmatched;
const isUnspecified = shapeDiff.isUnspecified;
const location = shapeDiff.location;
let updateSpecChoices: IPatchChoices = {
copy: [],
shapes: [],
isField: false,
isQueryParam: shapeDiff.location.isQueryParameter(),
};
if (isUnmatched) {
const allShapes = expected.unionWithActual(actual);
updateSpecChoices.shapes = Array.from(allShapes).map((i) => {
return {
coreShapeKind: i,
isValid: true,
};
});
}
if (isUnspecified) {
throw new InvariantViolationError(
'root object should never produce an unspecified diff'
);
}
////////////////
const expectedShapes = expected.expectedShapes();
const previews: IInteractionPreviewTab[] = [];
actual.interactionsGroupedByCoreShapeKind().forEach((i) => {
previews.push({
title: i.label,
invalid: !expectedShapes.has(i.kind),
interactionPointers: i.interactions,
assertion: [plain('expected'), code(expected.shapeName())],
jsonTrailsByInteractions: i.jsonTrailsByInteractions,
});
});
////////////////
return {
diffDescription,
updateSpecChoices,
toCommands: (choices: IPatchChoices): CQRSCommand[] => {
const { commands, rootShapeId } = builderInnerShapeFromChoices(
choices,
expected.allowedCoreShapeKindsByShapeId(),
actual,
currentSpecContext
);
const resetShapeCommand = resetBaseShape(location, rootShapeId);
return resetShapeCommand ? [...commands, resetShapeCommand] : commands;
},
previewTabs: sortBy(previews, (i) => !i.invalid),
};
}
function resetBaseShape(
location: DiffLocation,
newShapeId: string
): CQRSCommand | null {
const requestDescriptor = location.getRequestDescriptor();
const responseDescriptor = location.getResponseDescriptor();
const queryParametersId = location.getQueryParametersId();
if (requestDescriptor && requestDescriptor.requestId) {
return SetRequestBodyShape(
requestDescriptor.requestId,
ShapedBodyDescriptor(requestDescriptor.contentType, newShapeId, false)
);
} else if (
responseDescriptor &&
responseDescriptor.responseId &&
responseDescriptor.contentType
) {
return SetResponseBodyShape(
responseDescriptor.responseId,
ShapedBodyDescriptor(responseDescriptor.contentType, newShapeId, false)
);
} else if (queryParametersId) {
return SetQueryParametersShape(
queryParametersId,
QueryParametersShapeDescriptor(newShapeId)
);
} else {
// path_request and path_response are invalid locations that I don't believe hit this path
console.error('Unknown location received', location);
return null;
}
}
|
tony-aq/optic
|
workspaces/optic-domain/src/streams/spec-events.ts
|
<gh_stars>100-1000
import { Readable } from 'stream';
import { takeWhile } from 'axax/esnext/takeWhile';
import { fromJSONArray } from '../async-tools';
type Event = any; // TODO change to event typing
export function fromJSONStream(): (source: Readable) => AsyncIterable<Event> {
return fromJSONArray<Event>();
}
export function takeBatchesUntil(
batchCommitId: string
): (iterable: AsyncIterable<Event>) => AsyncIterable<Event> {
let seenBatchCommitId = false;
return takeWhile((event) => {
if (seenBatchCommitId) {
return false;
}
if (event.BatchCommitEnded?.batchId === batchCommitId) {
seenBatchCommitId = true;
}
return true;
});
}
|
tony-aq/optic
|
workspaces/api-checks/src/reports.ts
|
import { CheckResults } from './runner';
export function basicReport(results: CheckResults) {
if (results.hasFailures()) {
const failures = results.all().map((result) => `- ${result}`);
return `API checks failed\n${failures}`;
} else {
return 'All API checks passed';
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/shapes/thunks.ts
|
import { createAsyncThunk } from '@reduxjs/toolkit';
import * as Sentry from '@sentry/react';
import { IForkableSpectacle } from '@useoptic/spectacle';
import { JsonType } from '@useoptic/optic-domain';
import {
convertSpectacleChangeToChangeType,
SpectacleChange,
} from '../spectacleUtils';
import { ShapeId, ReduxField, ReduxShape } from './types';
const ShapeQuery = `
query X($shapeId: ID! $sinceBatchCommitId: String) {
shapeChoices(shapeId: $shapeId) {
id
jsonType
asObject {
fields {
name
fieldId
shapeId
contributions
changes(sinceBatchCommitId: $sinceBatchCommitId) {
added
changed
removed
}
}
}
asArray {
shapeId
}
}
}`;
type SpectacleField = {
name: string;
fieldId: string;
shapeId: string;
contributions: Record<string, string>;
changes: SpectacleChange;
};
type SpectacleArray = {
shapeId: string;
};
type SpectacleShape =
| {
id: string;
jsonType: JsonType.OBJECT;
asArray?: undefined;
asObject: {
fields: SpectacleField[];
};
}
| {
id: string;
jsonType: JsonType.ARRAY;
asArray: SpectacleArray;
asObject?: undefined;
}
| {
id: string;
jsonType: Exclude<JsonType, JsonType.OBJECT | JsonType.ARRAY>;
asArray?: undefined;
asObject?: undefined;
};
type SpectacleShapeResult = {
shapeChoices: SpectacleShape[];
};
const fetchSpectacleShape = async (
spectacle: IForkableSpectacle,
shapeId: string,
sinceBatchCommitId?: string
): Promise<SpectacleShapeResult> => {
const results = await spectacle.query<
SpectacleShapeResult,
{ shapeId: string; sinceBatchCommitId?: string }
>({
query: ShapeQuery,
variables: { shapeId, sinceBatchCommitId },
});
if (results.errors || !results.data) {
console.error(results.errors);
throw new Error(JSON.stringify(results.errors));
}
return results.data;
};
const fetchShapesAndChildren = async (
spectacle: IForkableSpectacle,
rootShapeId: string,
sinceBatchCommitId?: string
): Promise<{
shapeMap: Record<ShapeId, ReduxShape[]>;
fieldMap: Record<string, ReduxField>;
}> => {
// TODO we might want to have access to the current store to
// avoid fetching shapes we have already fetched
const shapeMap: Record<ShapeId, ReduxShape[]> = {};
const fieldMap: Record<string, ReduxField> = {};
let stack: ShapeId[] = [rootShapeId];
while (stack.length > 0) {
const results = await Promise.all(
stack.map(async (shapeId) => ({
result: await fetchSpectacleShape(
spectacle,
shapeId,
sinceBatchCommitId
),
shapeId,
}))
);
// Reset the stack and add in more shapes to fetch
stack = [];
for (const { result, shapeId: baseShapeId } of results) {
for (const shape of result.shapeChoices) {
if (!(baseShapeId in shapeMap)) {
shapeMap[baseShapeId] = [];
}
if (shape.jsonType === JsonType.OBJECT) {
const reduxFields: ReduxField[] = [];
for (const field of shape.asObject.fields) {
const { shapeId, fieldId } = field;
const reduxField = {
...field,
changes:
sinceBatchCommitId !== undefined
? convertSpectacleChangeToChangeType(field.changes)
: null,
};
// Continue fetching nodes in shape
if (!(shapeId in shapeMap && !stack.includes(shape.id))) {
stack.push(shapeId);
}
// Add transformed reduxField into field map and redux fields
fieldMap[fieldId] = reduxField;
reduxFields.push(reduxField);
}
const reduxShape: ReduxShape = {
shapeId: shape.id,
jsonType: JsonType.OBJECT,
asObject: {
fields: reduxFields,
},
};
shapeMap[baseShapeId].push(reduxShape);
} else if (shape.jsonType === JsonType.ARRAY) {
if (
!(
shape.asArray.shapeId in shapeMap &&
!stack.includes(shape.asArray.shapeId)
)
) {
stack.push(shape.asArray.shapeId);
}
const reduxShape: ReduxShape = {
shapeId: shape.id,
jsonType: JsonType.ARRAY,
asArray: {
shapeId: shape.asArray.shapeId,
},
};
shapeMap[baseShapeId].push(reduxShape);
} else {
const reduxShape: ReduxShape = {
shapeId: shape.id,
jsonType: shape.jsonType,
};
shapeMap[baseShapeId].push(reduxShape);
}
}
}
}
return { shapeMap, fieldMap };
};
export const fetchShapes = createAsyncThunk<
{
shapeMap: Record<ShapeId, ReduxShape[]>;
fieldMap: Record<string, ReduxField>;
},
{
spectacle: IForkableSpectacle;
rootShapeId: string;
sinceBatchCommitId?: string;
}
>('FETCH_SHAPES', async ({ spectacle, rootShapeId, sinceBatchCommitId }) => {
try {
const shapeMap = await fetchShapesAndChildren(
spectacle,
rootShapeId,
sinceBatchCommitId
);
return shapeMap;
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
});
|
tony-aq/optic
|
workspaces/ui-v2/src/hooks/util/index.ts
|
export * from './useDebouncedFn';
export * from './useStateWithSideEffect';
export * from './useRunOnKeypress';
|
tony-aq/optic
|
workspaces/ui-v2/src/components/layouts/CenteredColumn.tsx
|
<gh_stars>100-1000
import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Container } from '@material-ui/core';
export function CenteredColumn(props: any) {
const classes = useStyles();
return (
<div className={classes.centered}>
<Container maxWidth={props.maxWidth || 'lg'} style={props.style}>
{props.children}
</Container>
</div>
);
}
const useStyles = makeStyles((theme) => ({
centered: {
display: 'flex',
alignItems: 'center',
},
}));
|
tony-aq/optic
|
workspaces/spectacle/src/types.ts
|
<filename>workspaces/spectacle/src/types.ts<gh_stars>100-1000
import { ExecutionResult } from 'graphql';
import { EventEmitter } from 'events';
import {
ILearnedBodies,
IAffordanceTrailsDiffHashMap,
} from '@useoptic/cli-shared/build/diffs/initial-types';
import {
IHttpInteraction,
ShapeChoice,
JsonType,
} from '@useoptic/optic-domain';
import { endpoints, shapes } from '@useoptic/graph-lib';
import { CommandGenerator, ContributionsProjection } from './helpers';
import { IOpticCommandContext } from './in-memory';
////////////////////////////////////////////////////////////////////////////////
export interface IOpticEngine {
try_apply_commands(
commandsJson: string,
eventsJson: string,
batchId: string,
commitMessage: string,
clientId: string,
clientSessionId: string
): any;
affordances_to_commands(
json_affordances_json: string,
json_trail_json: string,
id_generator_strategy: string
): string;
get_shape_viewer_projection(spec: any): string;
get_contributions_projection(spec: any): string;
learn_shape_diff_affordances(
spec: any,
diff_results_json: string,
tagged_interactions_jsonl: string
): string;
learn_undocumented_bodies(
spec: any,
interactions_jsonl: string,
id_generator_strategy: string
): string;
spec_from_events(eventsJson: string): any;
spec_endpoint_delete_commands(
spec: any,
path_id: string,
method: string
): string;
spec_field_remove_commands(spec: any, field_id: string): string;
spec_field_edit_commands(
spec: any,
field_id: string,
requestedTypes: JsonType[],
id_generator_strategy: IOpticEngineIdGenerationStrategy
): string;
}
export enum IOpticEngineIdGenerationStrategy {
SEQUENTIAL = 'sequential',
UNIQUE = 'unique',
}
////////////////////////////////////////////////////////////////////////////////
export interface IOpticSpecRepository {
listEvents(): Promise<any[]>;
}
export interface IOpticSpecReadWriteRepository extends IOpticSpecRepository {
applyCommands(
commands: any[],
batchCommitId: string,
commitMessage: string,
commandContext: IOpticCommandContext
): Promise<void>;
changes: AsyncGenerator<number>;
notifications: EventEmitter;
resetToCommit(batchCommitId: string): Promise<void>;
}
////////////////////////////////////////////////////////////////////////////////
export interface ICapture {
captureId: string;
startedAt: string;
}
export interface StartDiffResult {
//notifications: EventEmitter;
onComplete: Promise<IOpticDiffService>;
}
export interface IOpticCapturesService {
listCaptures(): Promise<ICapture[]>;
loadInteraction(
captureId: string,
pointer: string
): Promise<IHttpInteraction>;
startDiff(diffId: string, captureId: string): Promise<StartDiffResult>;
}
////////////////////////////////////////////////////////////////////////////////
export interface IListDiffsResponse {
diffs: any[];
}
export interface IListUnrecognizedUrlsResponse {
urls: IUnrecognizedUrl[];
}
export interface IUnrecognizedUrl {
path: string;
method: string;
count: number;
}
export interface IOpticDiffService {
listDiffs(): Promise<IListDiffsResponse>;
listUnrecognizedUrls(): Promise<IListUnrecognizedUrlsResponse>;
learnUndocumentedBodies(
pathId: string,
method: string,
newPathCommands: any[]
): Promise<ILearnedBodies>;
learnShapeDiffAffordances(): Promise<IAffordanceTrailsDiffHashMap>;
}
////////////////////////////////////////////////////////////////////////////////
export interface IOpticDiffRepository {
findById(id: string): Promise<IOpticDiffService>;
add(id: string, diff: IOpticDiffService): Promise<void>;
}
////////////////////////////////////////////////////////////////////////////////
export interface IOpticConfigRepository {
addIgnoreRule(rule: string): Promise<void>;
getApiName(): Promise<string>;
listIgnoreRules(): Promise<string[]>;
}
export interface IOpticInteractionsRepository {
listById(id: string): Promise<any[]>;
set(id: string, interactions: any[]): Promise<void>;
}
////////////////////////////////////////////////////////////////////////////////
export interface IOpticContext {
opticEngine: IOpticEngine;
configRepository: IOpticConfigRepository;
specRepository: IOpticSpecReadWriteRepository;
capturesService: IOpticCapturesService;
diffRepository: IOpticDiffRepository;
}
////////////////////////////////////////////////////////////////////////////////
export interface IBaseSpectacle {
query<Result, Input = {}>(
options: SpectacleInput<Input>
): Promise<ExecutionResult<Result>>;
mutate<Result, Input = {}>(
options: SpectacleInput<Input>
): Promise<ExecutionResult<Result>>;
}
export interface IForkableSpectacle extends IBaseSpectacle {
fork(): Promise<IForkableSpectacle>;
}
// Record<ShapeId, ShapeChoice[]>
export type ShapeViewerProjection = Record<string, ShapeChoice[]>;
export interface SpectacleInput<
T extends {
[key: string]: any;
}
> {
query: string;
variables: T;
operationName?: string;
}
export type GraphQLContext = {
spectacleContext: () => {
opticContext: IOpticContext;
endpointsQueries: endpoints.GraphQueries;
shapeQueries: shapes.GraphQueries;
shapeViewerProjection: ShapeViewerProjection;
contributionsProjection: ContributionsProjection;
commandGenerator: CommandGenerator;
};
};
|
tony-aq/optic
|
workspaces/cli-shared/src/diffs/diffs.ts
|
<filename>workspaces/cli-shared/src/diffs/diffs.ts
//todo one time export from scala js, switch to types from Rust
import { IShapeTrail } from './shape-trail';
import { IInteractionTrail } from './interaction-trail';
import { IRequestSpecTrail } from './request-spec-trail';
import { IJsonTrail } from './json-trail';
// Top-level Diffs
export type IDiff =
| IUnmatchedQueryParametersShape
| IUnmatchedResponseBodyShape
| IUnmatchedRequestBodyShape
| IUnmatchedRequestUrl
| IUnmatchedRequestMethod
| IUnmatchedQueryParameters
| IUnmatchedResponseBodyContentType
| IUnmatchedRequestBodyContentType
| IUnmatchedResponseStatusCode;
export const DiffTypes = {
UnmatchedQueryParametersShape: 'UnmatchedQueryParametersShape',
UnmatchedResponseBodyShape: 'UnmatchedResponseBodyShape',
UnmatchedRequestBodyShape: 'UnmatchedRequestBodyShape',
UnmatchedRequestUrl: 'UnmatchedRequestUrl',
UnmatchedRequestMethod: 'UnmatchedRequestMethod',
UnmatchedQueryParameters: 'UnmatchedQueryParameters',
UnmatchedResponseBodyContentType: 'UnmatchedResponseBodyContentType',
UnmatchedRequestBodyContentType: 'UnmatchedRequestBodyContentType',
UnmatchedResponseStatusCode: 'UnmatchedResponseStatusCode',
};
export type IDiffWithShapeDiff =
| IUnmatchedQueryParametersShape
| IUnmatchedResponseBodyShape
| IUnmatchedRequestBodyShape;
export interface IUnmatchedQueryParametersShape {
UnmatchedQueryParametersShape: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
shapeDiffResult: IShapeDiffResult;
};
}
export interface IUnmatchedResponseBodyShape {
UnmatchedResponseBodyShape: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
shapeDiffResult: IShapeDiffResult;
};
}
export interface IUnmatchedRequestUrl {
UnmatchedRequestUrl: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
};
}
export interface IUnmatchedRequestMethod {
UnmatchedRequestMethod: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
};
}
export interface IUnmatchedResponseBodyContentType {
UnmatchedResponseBodyContentType: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
};
}
export interface IUnmatchedQueryParameters {
UnmatchedQueryParameters: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
};
}
export interface IUnmatchedRequestBodyContentType {
UnmatchedRequestBodyContentType: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
};
}
export interface IUnmatchedResponseStatusCode {
UnmatchedResponseStatusCode: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
};
}
export interface IUnmatchedRequestBodyShape {
UnmatchedRequestBodyShape: {
interactionTrail: IInteractionTrail;
requestsTrail: IRequestSpecTrail;
shapeDiffResult: IShapeDiffResult;
};
}
// Shape Diffs
export type IShapeDiffResult = IUnmatchedShape | IUnspecifiedShape;
export interface IUnmatchedShape {
UnmatchedShape: {
jsonTrail: IJsonTrail;
shapeTrail: IShapeTrail;
};
}
export interface IUnspecifiedShape {
UnspecifiedShape: {
jsonTrail: IJsonTrail;
shapeTrail: IShapeTrail;
};
}
//////////////////////////////
|
jeggburt/Angular-GettingStarted
|
APM-Start/src/app/products/products-detail.component.ts
|
<filename>APM-Start/src/app/products/products-detail.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
templateUrl: './products-detail.component.html',
styleUrls: ['./products-detail.component.css']
})
export class ProductsDetailComponent implements OnInit {
pageTitle: string = 'Product Detail'
constructor() { }
ngOnInit(): void {
}
}
|
Meghrup07/Task-List-App
|
src/app/task.ts
|
export class Task{
id:number;
name :string;
timeStamp:number;
constructor( nameN:string,idN:number,timeN:number){
this.name = nameN;
this.id=idN;
this.timeStamp=timeN;
}
}
|
Meghrup07/Task-List-App
|
src/app/app.component.ts
|
<reponame>Meghrup07/Task-List-App
import { Component, OnInit } from "@angular/core";
import { Task } from "./task";
@Component({
selector: "app-root",
templateUrl: "app.component.html",
styleUrls: ["app.component.css"],
})
export class AppComponent implements OnInit {
title = "Task list";
flag = 1;
toDoTaskCount = 0;
completedTaskCount = 0;
Tasks: Task[] = [];
dTask: Task[] = [];
taskText: string = "";
msg: string;
errMsg: string;
totalTaskToComplete: number;
completedTask: number;
today: number;
alreadyAddedTask: string;
addTask(msg: string) {
if (msg.length == 0) {
this.errMsg = "Task is not clear";
} else if (this.duplicateTask(msg) && this.flag) {
this.errMsg = "Task is already in the list";
} else {
this.today = Date.now();
this.Tasks.push(new Task(msg, this.toDoTaskCount, this.today));
this.errMsg = "";
this.taskText = "";
this.totalTaskToComplete = this.Tasks.length;
this.toDoTaskCount += 1;
}
}
duplicateTask(msg: string): number {
for (var i = 0; i < this.Tasks.length; i++) {
if (msg == this.Tasks[i].name) {
return 1;
}
}
return 0;
}
markAsComplete(task: Task) {
this.addDTask(task);
this.deleteTask(task);
}
editTask(task: Task) {
this.taskText = task.name;
this.deleteTask(task);
this.totalTaskToComplete = this.Tasks.length;
}
deleteTask(task: Task) {
this.Tasks = this.Tasks.filter((Tasks) => Tasks.id !== task.id);
this.totalTaskToComplete = this.Tasks.length;
}
reset() {
this.taskText = "";
}
dismiss() {
this.errMsg = "";
this.taskText = "";
}
addAnyWay(msg: string) {
if (msg.length == 0) {
msg = "Nothing to do";
}
this.flag = 0;
this.addTask(msg);
this.taskText = "";
}
addDTask(task: Task) {
this.dTask.push(new Task(task.name, this.completedTaskCount, Date.now()));
this.msg = task.name;
this.completedTask = this.dTask.length;
this.completedTaskCount += 1;
}
deleteDTask(task: Task) {
this.dTask = this.dTask.filter((dTask) => dTask.id !== task.id);
this.completedTask = this.dTask.length;
}
ngOnInit() {
this.addTask("Buy daily items from new-market");
this.addTask("Call Meghshyam At 6:30 PM");
this.addDTask(
new Task("this is completed task", this.completedTaskCount, Date.now())
);
}
}
|
FYDP-SAAC/rich-markdown-editor
|
src/menus/table.tsx
|
<filename>src/menus/table.tsx
import { TrashIcon } from "outline-icons";
export default function tableMenuItems() {
return [
{
name: "deleteTable",
tooltip: "Delete table",
icon: TrashIcon,
active: () => false,
},
];
}
|
FYDP-SAAC/rich-markdown-editor
|
src/queries/isNodeActive.ts
|
const isNodeActive = (type, attrs = undefined) => state => {
const { $from, to, node } = state.selection;
if (node) {
return attrs ? node.hasMarkup(type, attrs) : node.type === type;
}
return (
to <= $from.end() &&
(attrs ? $from.parent.hasMarkup(type, attrs) : $from.parent.type === type)
);
};
export default isNodeActive;
|
FYDP-SAAC/rich-markdown-editor
|
src/lib/ComponentView.tsx
|
<gh_stars>0
import * as React from "react";
import ReactDOM from "react-dom";
import { ThemeProvider } from "styled-components";
import { EditorView, Decoration } from "prosemirror-view";
import Extension from "../lib/Extension";
import Node from "../nodes/Node";
import { light as lightTheme, dark as darkTheme } from "../theme";
import Editor from "../";
type Component = (options: {
node: Node;
theme: typeof lightTheme;
isSelected: boolean;
isEditable: boolean;
getPos: () => number;
innerRef: (HTMLElement) => void;
}) => React.ReactElement;
export default class ComponentView {
component: Component;
editor: Editor;
extension: Extension;
node: Node;
view: EditorView;
getPos: () => number;
decorations: Decoration<{ [key: string]: any }>[];
isSelected = false;
containerElement: HTMLElement;
contentElement: HTMLElement;
dom: HTMLElement;
contentDOM: HTMLElement;
// See https://prosemirror.net/docs/ref/#view.NodeView
constructor(
component,
{ editor, extension, node, view, getPos, decorations }
) {
this.component = component;
this.editor = editor;
this.extension = extension;
this.getPos = getPos;
this.decorations = decorations;
this.node = node;
this.view = view;
this.containerElement = node.type.spec.inline
? document.createElement("span")
: document.createElement("div");
this.contentElement = node.type.spec.inline
? document.createElement("span")
: document.createElement("div");
this.renderElement();
this.dom = this.containerElement;
this.contentDOM = this.contentElement;
}
renderElement() {
const { dark } = this.editor.props;
const theme = this.editor.props.theme || (dark ? darkTheme : lightTheme);
const children = this.component({
theme,
node: this.node,
isSelected: this.isSelected,
isEditable: this.view.editable,
getPos: this.getPos,
innerRef: node => {
// move the contentDOM node inside the inner reference after rendering
if (node && this.contentDOM && !node.contains(this.contentDOM)) {
node.appendChild(this.contentDOM);
}
},
});
ReactDOM.render(
<ThemeProvider theme={theme}>{children}</ThemeProvider>,
this.containerElement
);
}
update(node) {
if (node.type !== this.node.type) {
return false;
}
this.node = node;
this.renderElement();
return true;
}
selectNode() {
if (this.view.editable) {
this.isSelected = true;
this.renderElement();
}
}
deselectNode() {
if (this.view.editable) {
this.isSelected = false;
this.renderElement();
}
}
stopEvent() {
return true;
}
destroy() {
ReactDOM.unmountComponentAtNode(this.containerElement);
this.containerElement = null;
this.contentElement = null;
}
ignoreMutation() {
return true;
}
}
|
FYDP-SAAC/rich-markdown-editor
|
src/types/index.ts
|
<reponame>FYDP-SAAC/rich-markdown-editor<filename>src/types/index.ts
import * as React from "react";
export type EmbedDescriptor = {
title?: string;
name?: string;
icon?: React.ReactNode;
matcher: (url: string) => boolean | [];
component: typeof React.Component;
};
|
FYDP-SAAC/rich-markdown-editor
|
src/components/LinkSearchResult.tsx
|
import * as React from "react";
import styled from "styled-components";
import { NextIcon } from "outline-icons";
type Props = {
onClick: (event: React.MouseEvent) => void;
selected: boolean;
title: string;
};
function LinkSearchResult({ title, ...rest }: Props) {
return (
<ListItem {...rest}>
<i>
<NextIcon light />
</i>
{title}
</ListItem>
);
}
const ListItem = styled.li<{
selected: boolean;
}>`
display: flex;
align-items: center;
height: 28px;
padding: 6px 8px 6px 0;
color: ${props => props.theme.toolbarItem};
font-family: ${props => props.theme.fontFamily};
font-size: 15px;
text-decoration: none;
overflow: hidden;
white-space: nowrap;
i {
visibility: ${props => (props.selected ? "visible" : "hidden")};
}
&:hover,
&:focus,
&:active {
font-weight: 500;
outline: none;
i {
visibility: visible;
}
}
`;
export default LinkSearchResult;
|
FYDP-SAAC/rich-markdown-editor
|
src/lib/markdown/checkboxes.ts
|
import MarkdownIt from "markdown-it";
import Token from "markdown-it/lib/token";
const CHECKBOX_REGEX = /\[(X|\s|_|-)\]\s(.*)?/i;
function matches(token: Token) {
return token.content.match(CHECKBOX_REGEX);
}
function isInline(token: Token): boolean {
return token.type === "inline";
}
function isParagraph(token: Token): boolean {
return token.type === "paragraph_open";
}
function looksLikeChecklist(tokens: Token[], index: number) {
return (
isInline(tokens[index]) &&
isParagraph(tokens[index - 1]) &&
matches(tokens[index])
);
}
export default function markdownItCheckbox(md: MarkdownIt): void {
// insert a new rule after the "inline" rules are parsed
md.core.ruler.after("inline", "checkboxes", state => {
const tokens = state.tokens;
// work backwards through the tokens and find text that looks like a checkbox
for (let i = tokens.length - 1; i > 0; i--) {
const matches = looksLikeChecklist(tokens, i);
if (matches) {
const value = matches[1];
const label = matches[2];
const checked = value.toLowerCase() === "x";
// convert surrounding list tokens
if (tokens[i - 3].type === "bullet_list_open") {
tokens[i - 3].type = "checkbox_list_open";
}
if (tokens[i + 3].type === "bullet_list_close") {
tokens[i + 3].type = "checkbox_list_close";
}
// remove [ ] [x] from list item label
tokens[i].content = label;
tokens[i].children[0].content = label;
// open list item and ensure checked state is transferred
tokens[i - 2].type = "checkbox_item_open";
if (checked === true) {
tokens[i - 2].attrs = [["checked", "true"]];
}
// close the list item
let j = i;
while (tokens[j].type !== "list_item_close") {
j++;
}
tokens[j].type = "checkbox_item_close";
}
}
return false;
});
}
|
FYDP-SAAC/rich-markdown-editor
|
src/menus/tableRow.tsx
|
import { TrashIcon, InsertAboveIcon, InsertBelowIcon } from "outline-icons";
export default function tableRowMenuItems(state, index) {
return [
{
name: "addRowAfter",
tooltip: "Insert row before",
icon: InsertAboveIcon,
attrs: { index: index - 1 },
active: () => false,
visible: index !== 0,
},
{
name: "addRowAfter",
tooltip: "Insert row after",
icon: InsertBelowIcon,
attrs: { index },
active: () => false,
},
{
name: "separator",
},
{
name: "deleteRow",
tooltip: "Delete row",
icon: TrashIcon,
active: () => false,
},
];
}
|
altenfreelance/react-oauth2-pkce
|
src/AuthService.ts
|
<filename>src/AuthService.ts
/* eslint-disable @typescript-eslint/camelcase */
import { createPKCECodes, PKCECodePair } from './pkce'
import { toUrlEncoded } from './util'
import jwtDecode from 'jwt-decode'
export interface AuthServiceProps {
clientId: string
clientSecret?: string
contentType?: string
location: Location
provider: string
authorizeEndpoint?: string
tokenEndpoint?: string
audience?: string
redirectUri?: string
scopes: string[]
autoRefresh?: boolean
refreshSlack?: number
}
export interface AuthTokens {
id_token: string
access_token: string
refresh_token: string
expires_in: number
expires_at?: number // calculated on login
token_type: string
}
export interface JWTIDToken {
given_name: string
family_name: string
name: string
email: string
}
export interface TokenRequestBody {
clientId: string
grantType: string
redirectUri?: string
refresh_token?: string
clientSecret?: string
code?: string
codeVerifier?: string
}
export class AuthService<TIDToken = JWTIDToken> {
props: AuthServiceProps
timeout?: number
constructor(props: AuthServiceProps) {
this.props = props
const code = this.getCodeFromLocation(window.location)
if (code !== null) {
this.fetchToken(code)
.then(() => {
this.restoreUri()
})
.catch((e) => {
this.removeItem('pkce')
this.removeItem('auth')
this.removeCodeFromLocation()
console.warn({ e })
})
} else if (this.props.autoRefresh) {
this.startTimer()
}
}
getUser(): {} {
const t = this.getAuthTokens()
if (null === t) return {}
const decoded = jwtDecode(t.id_token) as TIDToken
return decoded
}
getCodeFromLocation(location: Location): string | null {
const split = location.toString().split('?')
if (split.length < 2) {
return null
}
const pairs = split[1].split('&')
for (const pair of pairs) {
const [key, value] = pair.split('=')
if (key === 'code') {
return decodeURIComponent(value || '')
}
}
return null
}
removeCodeFromLocation(): void {
const [base, search] = window.location.href.split('?')
if (!search) {
return
}
const newSearch = search
.split('&')
.map((param) => param.split('='))
.filter(([key]) => key !== 'code')
.map((keyAndVal) => keyAndVal.join('='))
.join('&')
window.history.replaceState(
window.history.state,
'null',
base + (newSearch.length ? `?${newSearch}` : '')
)
}
getItem(key: string): string | null {
return window.localStorage.getItem(key)
}
removeItem(key: string): void {
window.localStorage.removeItem(key)
}
getPkce(): PKCECodePair {
const pkce = window.localStorage.getItem('pkce')
if (null === pkce) {
throw new Error('PKCE pair not found in local storage')
} else {
return JSON.parse(pkce)
}
}
setAuthTokens(auth: AuthTokens): void {
const { refreshSlack = 5 } = this.props
const now = new Date().getTime()
auth.expires_at = now + (auth.expires_in + refreshSlack) * 1000
window.localStorage.setItem('auth', JSON.stringify(auth))
}
getAuthTokens(): AuthTokens {
return JSON.parse(window.localStorage.getItem('auth') || '{}')
}
isPending(): boolean {
return (
window.localStorage.getItem('pkce') !== null &&
window.localStorage.getItem('auth') === null
)
}
isAuthenticated(): boolean {
return window.localStorage.getItem('auth') !== null
}
async logout(): Promise<boolean> {
this.removeItem('pkce')
this.removeItem('auth')
window.location.reload()
return true
}
async login(): Promise<void> {
this.authorize()
}
// this will do a full page reload and to to the OAuth2 provider's login page and then redirect back to redirectUri
authorize(): boolean {
const { clientId, provider, authorizeEndpoint, redirectUri, scopes, audience } = this.props
const pkce = createPKCECodes()
window.localStorage.setItem('pkce', JSON.stringify(pkce))
window.localStorage.setItem('preAuthUri', location.href)
window.localStorage.removeItem('auth')
const codeChallenge = pkce.codeChallenge
const query = {
clientId,
scope: scopes.join(' '),
responseType: 'code',
redirectUri,
...(audience && { audience }),
codeChallenge,
codeChallengeMethod: 'S256'
}
// Responds with a 302 redirect
const url = `${authorizeEndpoint || `${provider}/authorize`}?${toUrlEncoded(query)}`
window.location.replace(url)
return true
}
// this happens after a full page reload. Read the code from localstorage
async fetchToken(code: string, isRefresh = false): Promise<AuthTokens> {
const {
clientId,
clientSecret,
contentType,
provider,
tokenEndpoint,
redirectUri,
autoRefresh = true
} = this.props
const grantType = 'authorization_code'
let payload: TokenRequestBody = {
clientId,
...(clientSecret ? { clientSecret } : {}),
redirectUri,
grantType
}
if (isRefresh) {
payload = {
...payload,
grantType: 'refresh_token',
refresh_token: code
}
} else {
const pkce: PKCECodePair = this.getPkce()
const codeVerifier = pkce.codeVerifier
payload = {
...payload,
code,
codeVerifier
}
}
const response = await fetch(`${tokenEndpoint || `${provider}/token`}`, {
headers: {
'Content-Type': contentType || 'application/x-www-form-urlencoded'
},
method: 'POST',
body: toUrlEncoded(payload)
})
this.removeItem('pkce')
let json = await response.json()
if (isRefresh && !json.refresh_token) {
json.refresh_token = payload.refresh_token
}
this.setAuthTokens(json as AuthTokens)
if (autoRefresh) {
this.startTimer()
}
return this.getAuthTokens()
}
armRefreshTimer(refreshToken: string, timeoutDuration: number): void {
if (this.timeout) {
clearTimeout(this.timeout)
}
this.timeout = window.setTimeout(() => {
this.fetchToken(refreshToken, true)
.then(({ refresh_token: newRefreshToken, expires_at: expiresAt }) => {
if (!expiresAt) return
const now = new Date().getTime()
const timeout = expiresAt - now
if (timeout > 0) {
this.armRefreshTimer(newRefreshToken, timeout)
} else {
this.removeItem('auth')
this.removeCodeFromLocation()
}
})
.catch((e) => {
this.removeItem('auth')
this.removeCodeFromLocation()
console.warn({ e })
})
}, timeoutDuration)
}
startTimer(): void {
const authTokens = this.getAuthTokens()
if (!authTokens) {
return
}
const { refresh_token: refreshToken, expires_at: expiresAt } = authTokens
if (!expiresAt || !refreshToken) {
return
}
const now = new Date().getTime()
const timeout = expiresAt - now
if (timeout > 0) {
this.armRefreshTimer(refreshToken, timeout)
} else {
this.removeItem('auth')
this.removeCodeFromLocation()
}
}
restoreUri(): void {
const uri = window.localStorage.getItem('preAuthUri')
window.localStorage.removeItem('preAuthUri')
console.log({ uri })
if (uri !== null) {
window.location.replace(uri)
}
this.removeCodeFromLocation()
}
}
|
kevinelliott/acars-backend
|
src/entities/station.entity.ts
|
import {
AfterLoad,
Entity,
Column,
CreateDateColumn,
UpdateDateColumn,
JoinColumn,
PrimaryGeneratedColumn,
OneToMany,
OneToOne,
ManyToMany,
RelationCount,
createQueryBuilder,
ManyToOne,
} from 'typeorm';
import { Airframe } from './airframe.entity';
import { LeaderboardRank } from './leaderboard_rank.entity';
import { Message } from './message.entity';
import { StationMessageCount } from './station_message_count.entity';
import { User } from './user.entity';
@Entity('stations')
export class Station {
@PrimaryGeneratedColumn()
id: number;
@Column()
uuid: string;
@Column()
ident: string;
@Column({ name: 'ip_address' })
ipAddress: string;
@OneToMany(type => LeaderboardRank, rank => rank.station)
leaderboard_ranks: [];
@OneToMany(type => Message, message => message.station)
messages: [];
@OneToOne(type => StationMessageCount, stationMessageCount => stationMessageCount.station)
stationMessageCount: StationMessageCount;
public messagesCount?: number;
@ManyToMany(type => Airframe, airframe => airframe.stations)
airframes: Airframe[];
@Column({ name: 'source_application' })
sourceApplication: string;
@Column({ name: 'source_type' })
sourceType: string;
@Column({ name: 'source_protocol' })
sourceProtocol: string;
@Column({ name: 'user_id' })
userId: String;
@ManyToOne(type => User, user => user.stations)
@JoinColumn({ name: 'user_id' })
user: User;
@Column()
latitude: String;
@Column()
longitude: String;
@Column()
altitude: Number;
@Column({ name: 'nearest_airport_icao' })
nearestAirportIcao: string;
@Column()
description: string;
@Column({ name: 'system_platform' })
systemPlatform: string;
@Column({ name: 'system_os' })
systemOS: string;
@Column({ name: 'equipment_sdr' })
equipmentSdr: string;
@Column({ name: 'equipment_filters' })
equipmentFilters: string;
@Column({ name: 'equipment_antenna' })
equipmentAntenna: string;
@Column()
status: String;
@Column({ name: 'last_report_at' })
lastReportAt: Date;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
@AfterLoad()
setMessagesCount() {
// createQueryBuilder(Message)
// .where('station_id = :id', { id: this.id })
// .getCount()
// .then(result => {
// this.messagesCount = result;
// });
if (this.stationMessageCount != null) {
this.messagesCount = this.stationMessageCount.messagesCount;
}
}
}
|
kevinelliott/acars-backend
|
src/airframes/airframes.service.ts
|
<filename>src/airframes/airframes.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Airframe } from '../entities/airframe.entity';
import { Flight } from '../entities/flight.entity';
import { Message } from '../entities/message.entity';
import { Station } from '../entities/station.entity';
@Injectable()
export class AirframesService {
constructor(
@InjectRepository(Airframe) private readonly airframeRepository: Repository<Airframe>,
@InjectRepository(Flight) private readonly flightRepository: Repository<Station>,
@InjectRepository(Message) private readonly messageRepository: Repository<Message>,
@InjectRepository(Station) private readonly stationRepository: Repository<Station>,
) { }
async getAllAirframes(): Promise<Object> {
return await this.airframeRepository
.find({
order: { tail: 'ASC' },
});
}
async getAirframe(id): Promise<Object> {
return await this.airframeRepository
.findOne(id, {
relations: ["flights", "messages"]
});
}
}
|
kevinelliott/acars-backend
|
src/mail_report.service.ts
|
import { Injectable } from '@nestjs/common';
import { MailerService } from '@nestjs-modules/mailer';
import { Station } from './entities/station.entity';
import { User } from './entities/user.entity';
@Injectable()
export class MailReportService {
constructor(
private mailerService: MailerService,
) {}
async stationLeaderboardReport(user: User, station: Station, leaderboardRank: any) {
console.log(leaderboardRank);
this
.mailerService
.sendMail({
to: `${user.name} <${user.email}>`,
subject: `Leaderboard Report for Station ${station.ident}`,
template: 'report_leaderboard',
context: {
baseUrl: 'http://app.airframes.io',
stationIdent: station.ident,
rank: leaderboardRank.ranking,
points: leaderboardRank.points,
airframesLast24Hours: leaderboardRank.airframeLast24HoursCount,
airframesThisMonth: leaderboardRank.airframeThisMonthCount,
flightsLast24Hours: leaderboardRank.flightLast24HoursCount,
flightsThisMonth: leaderboardRank.flightThisMonthCount,
messagesLast24Hours: leaderboardRank.message24HoursCount,
messagesThisMonth: leaderboardRank.messageThisMonthCount,
},
})
.then(() => {})
.catch(() => {});
}
}
|
kevinelliott/acars-backend
|
src/user/stations/stations.service.ts
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Station } from '../../entities/station.entity';
@Injectable()
export class StationsService {
constructor(
@InjectRepository(Station, 'default') private readonly stationRepository: Repository<Station>,
@InjectRepository(Station, 'readonly') private readonly stationReadonlyRepository: Repository<Station>,
) {}
async findOne(id: Number): Promise<Station | undefined> {
return await this.stationReadonlyRepository
.findOne({
where: {
id: id
}
});
}
async save(station: Station): Promise<Station | undefined> {
return await this.stationRepository
.save(station);
}
}
|
kevinelliott/acars-backend
|
src/app.module.ts
|
<filename>src/app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { MailerModule } from '@nestjs-modules/mailer';
import { PugAdapter } from '@nestjs-modules/mailer/dist/adapters/pug.adapter';
import { TerminusModule } from '@nestjs/terminus';
import { OgmaModule } from '@ogma/nestjs-module';
import { ExpressParser } from '@ogma/platform-express';
import { configService } from './config/config.service';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AdminGeoJsonModule } from './admin/geojson/admin_geo_json.module';
import { AdminStatsModule } from './admin/stats/admin_stats.module';
import { AirframesModule } from './airframes/airframes.module';
import { EventsModule } from './events/events.module';
import { FlightsModule } from './flights/flights.module';
import { LeaderboardModule } from './leaderboard/leaderboard.module';
import { MessagesModule } from './messages/messages.module';
import { NatsModule } from './nats/nats.module';
import { ScheduleModule } from './schedule/schedule.module';
import { UsersModule } from './users/users.module';
import { UserModule } from './user/user.module';
import { UserStationsModule } from './user/stations/stations.module';
import { AuthModule } from './auth/auth.module';
import { HealthController } from './health/health.controller';
import { MailReportService } from './mail_report.service';
import { StationsModule } from './stations/stations.module';
@Module({
imports: [
OgmaModule.forRoot({
service: {
color: true,
json: false,
application: 'Airframes'
},
interceptor: {
http: ExpressParser,
ws: false,
gql: false,
rpc: false
}
}),
AuthModule,
TerminusModule,
MailerModule.forRoot({
transport: {
host: 'smtp.sendgrid.net',
port: 465,
secure: true,
auth: {
user: 'apikey',
pass: configService.getSendGridApiKey(),
}
},
defaults: {
from: '"Airframes" <<EMAIL>>',
},
preview: false,
template: {
dir: process.cwd() + '/src/templates/',
adapter: new PugAdapter(),
options: {
strict: true,
},
},
}),
AdminGeoJsonModule,
AdminStatsModule,
AirframesModule,
EventsModule,
FlightsModule,
LeaderboardModule,
MessagesModule,
NatsModule,
ScheduleModule,
StationsModule,
TypeOrmModule.forRoot(configService.getDefaultDbConfig()),
TypeOrmModule.forRoot(configService.getReadOnlyDbConfig()),
UsersModule,
UserModule,
UserStationsModule,
],
controllers: [AppController, HealthController],
providers: [
AppService,
MailReportService,
],
})
export class AppModule {
constructor(
private readonly connection: Connection,
private readonly readOnlyConnection: Connection
) {}
}
|
kevinelliott/acars-backend
|
src/admin/stats/admin_stats.module.ts
|
<filename>src/admin/stats/admin_stats.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AdminStatsController } from './admin_stats.controller';
import { AdminStatsService } from './admin_stats.service';
import { Airframe } from '../../entities/airframe.entity';
import { Flight } from '../../entities/flight.entity';
import { Message } from '../../entities/message.entity';
import { ReportMonthlyCount } from '../../entities/report_monthly_count.entity';
import { ReportDailyCount } from '../../entities/report_daily_count.entity';
import { ReportHourlyCount } from '../../entities/report_hourly_count.entity';
import { Station } from '../../entities/station.entity';
import { StationMessageCount } from '../../entities/station_message_count.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Airframe], 'readonly'),
TypeOrmModule.forFeature([Flight], 'readonly'),
TypeOrmModule.forFeature([Message], 'readonly'),
TypeOrmModule.forFeature([Station], 'readonly'),
TypeOrmModule.forFeature([StationMessageCount], 'readonly'),
TypeOrmModule.forFeature([ReportMonthlyCount], 'readonly'),
TypeOrmModule.forFeature([ReportDailyCount], 'readonly'),
TypeOrmModule.forFeature([ReportHourlyCount], 'readonly'),
],
controllers: [AdminStatsController],
providers: [AdminStatsService],
})
export class AdminStatsModule {}
|
kevinelliott/acars-backend
|
src/entities/leaderboard_rank.entity.ts
|
import {
Entity,
Column,
CreateDateColumn,
UpdateDateColumn,
PrimaryGeneratedColumn,
ManyToOne,
JoinColumn
} from 'typeorm';
import { Station } from './station.entity';
import { Leaderboard } from './leaderboard.entity';
@Entity('leaderboard_ranks')
export class LeaderboardRank {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => Leaderboard, leaderboard => leaderboard.ranks)
@JoinColumn({ name: 'leaderboard_id' })
leaderboard: Leaderboard;
@Column({ name: 'ranking'})
ranking: Number;
@ManyToOne(type => Station, station => station.leaderboard_ranks)
@JoinColumn({ name: 'station_id' })
station: Station;
@Column({ name: 'airframe_all_time_count'})
airframeAllTimeCount: Number;
@Column({ name: 'airframe_this_month_count'})
airframeThisMonthCount: Number;
@Column({ name: 'airframe_last_24_hours_count'})
airframeLast24HoursCount: Number;
@Column({ name: 'flight_all_time_count'})
flightAllTimeCount: Number;
@Column({ name: 'flight_this_month_count'})
flightThisMonthCount: Number;
@Column({ name: 'flight_last_24_hours_count'})
flightLast24HoursCount: Number;
@Column({ name: 'message_all_time_count'})
messageAllTimeCount: Number;
@Column({ name: 'message_this_month_count'})
messageThisMonthCount: Number;
@Column({ name: 'message_last_24_hours_count'})
messageLast24HoursCount: Number;
@Column({ name: 'points'})
points: Number;
// @Column({ name: 'points_detail'})
// pointsDetail: Object;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}
|
kevinelliott/acars-backend
|
src/admin/stats/admin_stats.controller.ts
|
import { Controller, Get, Param } from '@nestjs/common';
import { AdminStatsService } from './admin_stats.service';
@Controller('admin/stats')
export class AdminStatsController {
constructor(private readonly adminStatsService: AdminStatsService) {}
@Get()
getStats(): Promise<Object> {
return this.adminStatsService.getStats();
}
@Get('airlines')
getAirlines(): Promise<Object> {
return this.adminStatsService.getAirlines();
}
@Get('airframes')
getAirframes(): Promise<Object> {
return this.adminStatsService.getAirframes();
}
@Get('errors')
getErrors(): Promise<Object> {
return this.adminStatsService.getErrors();
}
@Get('flights')
getFlights(): Promise<Object> {
return this.adminStatsService.getFlights();
}
@Get('frequencies')
getFrequencies(): Promise<Object> {
return this.adminStatsService.getFrequencies();
}
@Get('labels')
getLabels(): Promise<Object> {
return this.adminStatsService.getLabels();
}
@Get('stations')
getStations(): Promise<Object> {
return this.adminStatsService.getStations();
}
@Get('stations/:id')
getStation(@Param() params): Promise<Object> {
return this.adminStatsService.getStationCounts(params.id);
}
}
|
kevinelliott/acars-backend
|
src/stations/stations.service.ts
|
<gh_stars>1-10
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Station } from '../entities/station.entity';
@Injectable()
export class StationsService {
constructor(
@InjectRepository(Station, 'default') private readonly stationRepository: Repository<Station>,
@InjectRepository(Station, 'readonly') private readonly stationRepositoryReadOnly: Repository<Station>,
) {}
async findOne(id: string): Promise<Station | undefined> {
return await this.stationRepositoryReadOnly
.findOne({
relations: ['user'],
where: {
id: id
}
});
}
}
|
kevinelliott/acars-backend
|
src/user/stations/stations.controller.ts
|
import { Controller, Get, Req, Request, UseGuards, Post } from '@nestjs/common';
import { StationsService } from './stations.service';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
@Controller('user')
export class StationsController {
constructor(private readonly stationService: StationsService) {}
@UseGuards(JwtAuthGuard)
@Post('stations/:id')
async saveStation(@Req() req): Promise<Object> {
console.log(req.body);
return this.stationService.save(req.body.station);
}
}
|
kevinelliott/acars-backend
|
src/config/config.service.ts
|
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Logger } from '@nestjs/common';
require('dotenv').config();
class ConfigService {
constructor(
private logger: Logger,
private env: { [k: string]: string | undefined }
) { }
private getValue(key: string, throwOnMissing = true): string {
const value = this.env[key];
if (requiredVars.includes(key) && !value && throwOnMissing) {
throw new Error(`config error - missing env.${key}`);
}
return value;
}
public ensureValues(keys: string[]) {
keys.forEach(k => this.getValue(k, true));
return this;
}
public getPort() {
return this.getValue('PORT', true);
}
public isProduction() {
const mode = this.getValue('MODE', false);
return mode != 'DEV';
}
public getNatsConfig() {
return {
natsUrl: 'https://' + this.getValue('NATS_HOST') + ':' + this.getValue('NATS_PORT'),
}
}
public getSendGridApiKey() {
return this.getValue('SENDGRID_API_KEY');
}
public getDefaultDbConfig(): TypeOrmModuleOptions {
return {
name: 'default',
type: 'postgres',
host: this.getValue('DATABASE_HOST'),
port: parseInt(this.getValue('DATABASE_PORT')),
username: this.getValue('DATABASE_USER'),
password: this.getValue('<PASSWORD>'),
database: this.getValue('DATABASE_NAME'),
entities: ['dist/**/*.entity{.ts,.js}'],
poolErrorHandler: function(err: any) {
this.logger.warn(err);
},
// logging: ['query', 'error'],
logging: ['error'],
migrationsTableName: 'migration',
migrations: ['src/migration/*.ts'],
cli: {
migrationsDir: 'src/migration',
},
synchronize: false,
cache: true,
ssl: process.env.DATABASE_SSL === 'true' || process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod',
};
}
public getReadOnlyDbConfig(): TypeOrmModuleOptions {
return {
name: '<PASSWORD>',
type: 'postgres',
host: this.getValue('READONLY_DATABASE_HOST'),
port: parseInt(this.getValue('READONLY_DATABASE_PORT')),
username: this.getValue('READONLY_DATABASE_USER'),
password: this.getValue('<PASSWORD>DATABASE_PASS'),
database: this.getValue('READONLY_DATABASE_NAME'),
entities: ['dist/**/*.entity{.ts,.js}'],
poolErrorHandler: function(err: any) {
this.logger.error(err);
},
logging: ['error'],
synchronize: false,
cache: false,
ssl: process.env.DATABASE_SSL === 'true' || process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod' ? { rejectUnauthorized: false } : false,
};
}
}
const requiredVars = [
'DATABASE_HOST',
'DATABASE_PORT',
'DATABASE_USER',
'DATABASE_NAME',
'NATS_HOST',
'NATS_PORT',
'READONLY_DATABASE_HOST',
'READONLY_DATABASE_PORT',
'READONLY_DATABASE_USER',
'READONLY_DATABASE_NAME',
];
const logger = new Logger('ConfigService');
const configService = new ConfigService(logger, process.env)
.ensureValues(requiredVars);
export { configService };
|
kevinelliott/acars-backend
|
src/airframes/airframes.module.ts
|
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AirframesController } from './airframes.controller';
import { AirframesService } from './airframes.service';
import { Airframe } from '../entities/airframe.entity';
import { Flight } from '../entities/flight.entity';
import { Message } from '../entities/message.entity';
import { Station } from '../entities/station.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Airframe]),
TypeOrmModule.forFeature([Flight]),
TypeOrmModule.forFeature([Message]),
TypeOrmModule.forFeature([Station]),
],
controllers: [AirframesController],
providers: [AirframesService],
})
export class AirframesModule {}
|
kevinelliott/acars-backend
|
src/admin/stats/admin_stats.service.ts
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as moment from 'moment';
import { Airframe } from '../../entities/airframe.entity';
import { Flight } from '../../entities/flight.entity';
import { Message } from '../../entities/message.entity';
import { Station } from '../../entities/station.entity';
import { StationMessageCount } from '../../entities/station_message_count.entity';
import { ReportMonthlyCount } from 'src/entities/report_monthly_count.entity';
import { ReportDailyCount } from 'src/entities/report_daily_count.entity';
import { ReportHourlyCount } from 'src/entities/report_hourly_count.entity';
@Injectable()
export class AdminStatsService {
constructor(
@InjectRepository(Airframe, 'readonly') private readonly airframeRepository: Repository<Airframe>,
@InjectRepository(Flight, 'readonly') private readonly flightRepository: Repository<Flight>,
@InjectRepository(Message, 'readonly') private readonly messageRepository: Repository<Message>,
@InjectRepository(ReportMonthlyCount, 'readonly') private readonly reportMonthlyCountRepository: Repository<ReportMonthlyCount>,
@InjectRepository(ReportDailyCount, 'readonly') private readonly reportDailyCountRepository: Repository<ReportDailyCount>,
@InjectRepository(ReportHourlyCount, 'readonly') private readonly reportHourlyCountRepository: Repository<ReportHourlyCount>,
@InjectRepository(Station, 'readonly') private readonly stationRepository: Repository<Station>,
@InjectRepository(StationMessageCount, 'readonly') private readonly stationMessageCountRepository: Repository<Station>,
) { }
async getAirframeCount(): Promise<Object> {
return await this.airframeRepository
.createQueryBuilder('airframes')
.leftJoin('airframes.flights', 'flights')
.leftJoin('airframes.messages', 'messages')
// .leftJoin('airframes.stations', 'stations')
.select('airframes.tail', 'tail')
.addSelect('COUNT(DISTINCT(flights.id)) as flight_count')
.addSelect('COUNT(DISTINCT(messages.id)) as message_count')
// .addSelect('COUNT(DISTINCT(stations.id)) as station_count')
.groupBy('airframes.tail')
.getRawMany();
}
async getMessageErrorStats(): Promise<Object> {
return await this.messageRepository.createQueryBuilder('messages')
.groupBy('error')
.select('error, count(error)')
.getRawMany();
}
async getMessageLabelStats(): Promise<Object> {
return await this.messageRepository.createQueryBuilder('messages')
.groupBy('label')
.select('label, count(label)')
.getRawMany();
}
async getFlightCount(): Promise<Object> {
return await this.flightRepository.createQueryBuilder('flights')
.groupBy('flight')
.select('flight, COUNT(flight)')
.getRawMany();
}
async getReportMonthlyCounts(id): Promise<Object> {
return await this.reportMonthlyCountRepository.createQueryBuilder('report_monthly_counts')
.where({
stationId: id
})
.getMany();
}
async getReportDailyCounts(id): Promise<Object> {
return await this.reportDailyCountRepository.find({
where: {
stationId: id
}
});
}
async getReportHourlyCounts(id): Promise<Object> {
return await this.reportHourlyCountRepository.createQueryBuilder('report_hourly_counts')
.where({
stationId: id
})
.getMany();
}
async getStationMessageCount(id): Promise<Object> {
return await this.stationMessageCountRepository.createQueryBuilder('station_message_counts')
.where({
stationId: id
})
.getOne();
}
async getStats(): Promise<Object> {
let airframeCount = await this.getAirframeCount();
let errorStats = await this.getMessageErrorStats();
let labelStats = await this.getMessageLabelStats();
let flightCount = await this.getFlightCount();
return {
airlines: [],
airframes: airframeCount,
errors: errorStats,
flights: flightCount,
frequencies: [],
labels: labelStats,
stations: [],
};
}
async getAirlines(): Promise<Object> {
let airlines = [];
return {
airlines: airlines
};
}
async getAirframes(): Promise<Object> {
let airframeCount = await this.getAirframeCount();
return {
airframes: airframeCount
};
}
async getErrors(): Promise<Object> {
let errorStats = await this.getMessageErrorStats();
return {
errors: errorStats
};
}
async getFlights(): Promise<Object> {
let flightCount = await this.getFlightCount();
return {
flights: flightCount
};
}
async getFrequencies(): Promise<Object> {
const frequencies: any = await this.messageRepository.createQueryBuilder('messages')
.select('frequency', 'frequency')
.addSelect('count(*)', 'message_count')
.groupBy('frequency')
.orderBy('message_count', 'DESC')
.getMany();
return {
frequencies: frequencies
};
}
async getLabels(): Promise<Object> {
let labelStats = await this.getMessageLabelStats();
return {
labels: labelStats
};
}
async getStations(): Promise<Object> {
const stations: any = await this.stationRepository.createQueryBuilder('stations')
.getMany();
const stationCounts = await stations.reduce(async(acc, station: any) => {
const accumulator = await acc;
accumulator.push(await this.getStationCounts(station));
return accumulator;
}, [])
return {
stations: stationCounts,
};
}
async getStationCounts(station): Promise<Object> {
const reportMonthlyCounts: any = await this.getReportMonthlyCounts(station.id);
const reportDailyCounts: any = await this.getReportDailyCounts(station.id);
const reportHourlyCounts: any = await this.getReportHourlyCounts(station.id);
const stationMessageCount: any = await this.getStationMessageCount(station.id);
const monthly = reportMonthlyCounts.reduce((map, rmc: any) => {
const monthString = moment(rmc.date).format('YYYY-MM');
map[monthString] = rmc.messagesCount;
return map;
}, {});
const daily = reportDailyCounts.reduce((map, rmc: any) => {
console.log(`report_daily_counts: ${rmc.date.toString()}`);
const dayString = moment(rmc.date).format('YYYY-MM-DD');
map[dayString] = rmc.messagesCount;
return map;
}, {});
return {
id: station.id,
ident: station.ident,
messages: {
all: Number(stationMessageCount.messagesCount),
monthly: monthly,
daily: daily,
}
}
}
}
|
kevinelliott/acars-backend
|
src/events/events.gateway.ts
|
<reponame>kevinelliott/acars-backend
import { Logger, UseInterceptors} from '@nestjs/common';
import {
OnGatewayConnection,
OnGatewayDisconnect,
WebSocketGateway,
WebSocketServer,
OnGatewayInit,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
@WebSocketGateway({ origins: '*:*', transports: ['polling', 'websocket'] })
export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer() server: Server;
private logger: Logger = new Logger(EventsGateway.name);
connectionsCount: number = 0;
connections: Map<string, Socket> = new Map();
async afterInit() {
this.logger.log('WebSocketGateway initialized.');
}
async handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Browser connected: ${client.id}`);
this.connectionsCount++;
this.connections.set(client.id, client);
const clients = new Array();
Array.from(this.connections.values()).forEach((value: Socket) => {
clients.push({
id: value.id,
rooms: value.rooms,
handshake: value.handshake,
});
});
this.server.emit('clients', clients);
this.server.emit('events', 'browser-connected');
}
async handleDisconnect(client: Socket) {
this.logger.log(`Browser disconnected: ${client.id}`);
this.connectionsCount--;
this.connections.delete(client.id);
const clients = new Array();
for(let [key, value] of this.connections) {
clients.push({
id: value.id,
rooms: value.rooms,
handshake: value.handshake,
});
}
this.server.emit('clients', clients);
this.server.emit('events', 'browser-disconnected');
}
async broadcast(subject: string, data: any) {
if (this.connectionsCount > 0) {
// this.logger.log("Broadcasting '" + subject + "' to " + this.connectionsCount + " browsers.");
try {
this.server.emit('events', 'broadcast');
this.server.emit(subject, data);
} catch (e) {
this.logger.log(e);
}
} else {
// this.logger.log('No browser connections, skipping broadcast.')
}
}
// @SubscribeMessage('events')
// handleEvents(@MessageBody() data: any): Observable<WsResponse<number>> {
// return from([1, 2, 3]).pipe(map(item => ({ event: 'events', data: item })));
// }
// @SubscribeMessage('identity')
// async identity(@MessageBody() data: number): Promise<number> {
// return data;
// }
}
|
kevinelliott/acars-backend
|
src/entities/user.entity.ts
|
import {
Entity,
Column,
CreateDateColumn,
JoinColumn,
UpdateDateColumn,
PrimaryGeneratedColumn,
OneToMany,
ManyToOne,
RelationCount,
AfterLoad,
} from 'typeorm';
import * as crypto from 'crypto';
import { Station } from './station.entity';
@Entity('users')
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
@OneToMany(type => Station, station => station.user)
stations: [];
@Column()
username: string;
@Column()
password: string;
@Column({ name: 'encrypted_password' })
encryptedPassword: string;
@Column()
name: string;
@Column()
email: string;
@Column()
role: String;
@Column()
status: string;
@Column({ name: 'confirmation_token' })
confirmationToken: string;
@Column({ name: 'api_key' })
apiKey: string;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
public gravatarUrl: string;
@AfterLoad()
setGravatarUrl() {
if (this.email != null) {
const size = 100;
const md5 = crypto.createHash('md5').update(this.email).digest("hex");
this.gravatarUrl = "https://www.gravatar.com/avatar/" + md5 + "?s=" + size;
}
}
}
|
kevinelliott/acars-backend
|
src/entities/airframe.entity.ts
|
import {
AfterLoad,
Entity,
Column,
CreateDateColumn,
UpdateDateColumn,
PrimaryGeneratedColumn,
OneToMany,
RelationCount,
ManyToMany,
JoinTable,
} from 'typeorm';
import { Message } from './message.entity';
import { Flight } from './flight.entity';
import { Station } from './station.entity';
@Entity('airframes')
export class Airframe {
@PrimaryGeneratedColumn()
id: number;
@Column()
tail: string;
@OneToMany(type => Message, message => message.airframe)
messages: Message[];
public messagesCount?: number;
@OneToMany(type => Flight, flight => flight.airframe)
flights: Flight[];
@RelationCount('flights')
public flightsCount?: number;
@ManyToMany(type => Station, station => station.airframes)
@JoinTable({
name: 'messages',
joinColumn: {
name: 'airframe_id',
referencedColumnName: 'id',
},
inverseJoinColumn: {
name: 'station_id',
referencedColumnName: 'id',
},
})
stations: Station[];
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
@AfterLoad()
setMessagesCount() {
this.messagesCount = 10000000;
}
}
|
kevinelliott/acars-backend
|
src/flights/flights.controller.ts
|
<reponame>kevinelliott/acars-backend<filename>src/flights/flights.controller.ts
import { Controller, Get, Param } from '@nestjs/common';
import { FlightsService } from './flights.service';
@Controller('flights')
export class FlightsController {
constructor(private readonly flightsService: FlightsService) {}
@Get()
async findAll(@Param() params): Promise<Object> {
return this.flightsService.getAllFlights();
}
@Get('active')
async findActive(@Param() params): Promise<Object> {
return this.flightsService.getActiveFlights();
}
@Get(':id')
async findOne(@Param() params): Promise<Object> {
return this.flightsService.getFlight(params.id);
}
}
|
kevinelliott/acars-backend
|
src/leaderboard/leaderboard.module.ts
|
<reponame>kevinelliott/acars-backend
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { LeaderboardController } from './leaderboard.controller';
import { LeaderboardService } from './leaderboard.service';
import { Leaderboard } from '../entities/leaderboard.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Leaderboard], 'readonly'),
],
controllers: [LeaderboardController],
providers: [LeaderboardService],
exports: [LeaderboardService],
})
export class LeaderboardModule {}
|
kevinelliott/acars-backend
|
src/schedule/schedule.module.ts
|
<reponame>kevinelliott/acars-backend
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EventsModule } from '../events/events.module';
// import { EventsGateway } from '../events/events.gateway';
import { Flight } from '../entities/flight.entity';
import { Leaderboard } from '../entities/leaderboard.entity';
import { LeaderboardRank } from '../entities/leaderboard_rank.entity';
import { Message } from '../entities/message.entity';
import { ScheduleService } from './schedule.service';
import { Station } from '../entities/station.entity';
@Module({
imports: [
EventsModule,
TypeOrmModule.forFeature([Flight]),
TypeOrmModule.forFeature([Leaderboard]),
TypeOrmModule.forFeature([LeaderboardRank]),
TypeOrmModule.forFeature([Message]),
TypeOrmModule.forFeature([Station])
],
providers: [ScheduleService],
})
export class ScheduleModule {}
|
kevinelliott/acars-backend
|
src/entities/message.entity.ts
|
import {
Entity,
Column,
CreateDateColumn,
UpdateDateColumn,
PrimaryGeneratedColumn,
ManyToOne,
OneToMany,
JoinColumn
} from 'typeorm';
import { Airframe } from './airframe.entity';
import { Flight } from './flight.entity';
import { MessageDecoding } from './message_decoding.entity';
import { Station } from './station.entity';
@Entity('messages')
export class Message {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => Station, station => station.messages)
@JoinColumn({ name: 'station_id' })
station: Station;
@ManyToOne(type => Airframe, airframe => airframe.messages)
@JoinColumn({ name: 'airframe_id' })
airframe: Airframe;
@ManyToOne(type => Flight, flight => flight.messages)
@JoinColumn({ name: 'flight_id' })
flight: Flight;
@Column()
source: string;
@Column({ name: 'source_type' })
sourceType: string;
@Column({ name: 'link_direction' })
linkDirection: string;
@Column({ name: 'from_hex' })
fromHex: string;
@Column({ name: 'to_hex' })
toHex: string;
@Column()
timestamp: Date;
@Column()
tail: string;
@Column({ name: 'flight' })
flightNumber: string;
@Column()
channel: number;
@Column()
frequency: number;
@Column()
level: number;
@Column()
error: number;
@Column()
mode: string;
@Column()
label: string;
@Column({ name: 'block_id' })
blockId: string;
@Column({ name: 'message_number' })
messageNumber: string;
@Column()
ack: string;
@Column('text')
data: string;
@Column('text')
text: string;
@Column({ name: 'departing_airport' })
departingAirport: string;
@Column({ name: 'destination_airport' })
destinationAirport: string;
@Column('float')
latitude: number;
@Column('float')
longitude: number;
@Column()
altitude: number;
@OneToMany(type => MessageDecoding, message_decoding => message_decoding.message)
message_decodings: MessageDecoding[];
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}
|
kevinelliott/acars-backend
|
src/stations/stations.module.ts
|
<reponame>kevinelliott/acars-backend<filename>src/stations/stations.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { StationsService } from './stations.service';
import { Station } from 'src/entities/station.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Station], 'default'),
TypeOrmModule.forFeature([Station], 'readonly'),
],
providers: [StationsService],
exports: [StationsService],
})
export class StationsModule {}
|
kevinelliott/acars-backend
|
src/user/user.controller.ts
|
<reponame>kevinelliott/acars-backend
import { Controller, Get, Req, Request, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get('myip')
async current(@Req() req): Promise<Object> {
const ipAddress = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress;
console.log(ipAddress.split(':').pop());
return this.userService.myIp(ipAddress);
}
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
}
|
kevinelliott/acars-backend
|
src/entities/flight.entity.ts
|
import {
Entity,
Column,
CreateDateColumn,
JoinColumn,
UpdateDateColumn,
PrimaryGeneratedColumn,
OneToMany,
ManyToOne,
RelationCount,
} from 'typeorm';
import { Airframe } from './airframe.entity';
import { Message } from './message.entity';
@Entity('flights')
export class Flight {
@PrimaryGeneratedColumn()
id: number;
@Column()
flight: string;
@ManyToOne(type => Airframe, airframe => airframe.messages)
@JoinColumn({ name: 'airframe_id' })
airframe: Airframe;
@OneToMany(type => Message, message => message.flight)
messages: [];
@RelationCount('messages')
public messagesCount?: number;
@Column()
status: string;
@Column({ name: 'departing_airport' })
departingAirport: string;
@Column({ name: 'destination_airport' })
destinationAirport: string;
@Column()
latitude: Number;
@Column()
longitude: Number;
@Column()
altitude: Number;
@Column()
track: Number;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}
|
kevinelliott/acars-backend
|
src/auth/auth.service.ts
|
import { Injectable, Logger, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { MailerService } from '@nestjs-modules/mailer';
import * as crypto from 'crypto';
import { UsersService } from '../users/users.service';
import { User } from '../entities/user.entity';
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
private mailerService: MailerService,
) {}
async validateUser(email: string, pass: string): Promise<any> {
console.log('auth');
const user = await this.usersService.findOneByEmail(email);
if (user && user.password === pass) {
const { password, ...result } = user;
return result;
}
return null;
}
async confirm(token: any) {
console.log('confirm');
console.log(token);
const user = await this.usersService.findOneByConfirmationToken(token);
if (user) {
user.status = 'active';
await this.usersService.save(user);
return { confirmed: true };
}
throw new BadRequestException('Unable to find pending confirmation');
}
async login(user: any) {
const payload = { email: user.email, username: user.username, sub: user.userId };
return {
user: {
id: user.id,
username: user.username,
name: user.name,
email: user.email,
gravatarUrl: user.gravatarUrl,
role: user.role,
stations: user.stations,
apiKey: user.apiKey,
status: user.status,
},
accessToken: this.jwtService.sign(payload),
};
}
async mail(user: User) {
console.log(user);
this
.mailerService
.sendMail({
to: `${user.name} <${user.email}>`,
subject: 'Airframes Registration Confirmation',
template: 'confirmation',
context: {
baseUrl: 'http://app.airframes.io',
name: user.name,
email: user.email,
username: user.username,
confirmationToken: user.confirmationToken,
},
})
.then(() => {})
.catch(() => {});
}
async register(data: any) {
console.log(data);
let existingUser = await this.usersService.findOneByEmail(data.email);
if (existingUser) {
throw new BadRequestException('Email already in use');
}
existingUser = await this.usersService.findOneByUsername(data.username);
if (existingUser) {
throw new BadRequestException('Username already in use');
}
let userDto = new User();
userDto.email = data.email;
userDto.name = data.name;
userDto.username = data.username;
userDto.password = <PASSWORD>;
userDto.encryptedPassword = <PASSWORD>;
userDto.confirmationToken = crypto.createHash('md5').digest("hex");
const user = await this.usersService.create(userDto);
const { password, encryptedPassword, ...result } = user;
const mailResult = await this.mail(user);
return {
user: result,
message: 'Check your email to verify your new account.',
};
}
}
|
kevinelliott/acars-backend
|
src/users/users.service.ts
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User, 'default') private readonly userRepository: Repository<User>,
@InjectRepository(User, 'readonly') private readonly userReadonlyRepository: Repository<User>,
) {}
async findOne(username: string): Promise<User | undefined> {
return await this.userReadonlyRepository
.findOne({
relations: ['stations', 'stations.stationMessageCount'],
where: {
username: username
}
});
}
async findOneById(id: String): Promise<User | undefined> {
return await this.userReadonlyRepository
.findOne({
relations: ['stations', 'stations.stationMessageCount'],
where: {
id: id
}
});
}
async findOneByConfirmationToken(token: string): Promise<User | undefined> {
return await this.userReadonlyRepository
.findOne({
where: {
confirmationToken: token
}
});
}
async findOneByEmail(email: string): Promise<User | undefined> {
return await this.userReadonlyRepository
.findOne({
relations: ['stations', 'stations.stationMessageCount'],
where: {
email: email
}
});
}
async findOneByUsername(username: string): Promise<User | undefined> {
return await this.userReadonlyRepository
.findOne({
relations: ['stations', 'stations.stationMessageCount'],
where: {
username: username
}
});
}
async create(user: User): Promise<User | undefined> {
return await this.userRepository
.save(user);
}
async save(user: User): Promise<User | undefined> {
return await this.userRepository.save(user);
}
}
|
kevinelliott/acars-backend
|
src/auth/constants.ts
|
<reponame>kevinelliott/acars-backend<gh_stars>1-10
export const jwtConstants = {
secret: '<PASSWORD>!',
};
|
kevinelliott/acars-backend
|
src/flights/flights.service.ts
|
<reponame>kevinelliott/acars-backend<gh_stars>1-10
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Flight } from '../entities/flight.entity';
import { OgmaLogger, OgmaService } from '@ogma/nestjs-module';
@Injectable()
export class FlightsService {
constructor(
@InjectRepository(Flight, 'readonly') private readonly flightRepository: Repository<Flight>,
@OgmaLogger(FlightsService) private readonly logger: OgmaService,
) { }
async getAllFlights(): Promise<Object> {
this.logger.info('Getting all flights');
return await this.flightRepository
.find({
relations: ["airframe"]
});
}
async getFlight(id): Promise<Object> {
this.logger.info(`Getting flight ${id}`);
return await this.flightRepository
.findOne(id, {
relations: ["airframe", "messages"]
});
}
async getActiveFlights(): Promise<Object> {
this.logger.info(`Getting active flights`);
return await this.flightRepository
.find({
relations: ['airframe'],
where: {
status: 'in-flight'
}
});
}
}
|
kevinelliott/acars-backend
|
src/nats/nats.controller.ts
|
import { Controller, Injectable, Logger } from '@nestjs/common';
import { EventPattern } from '@nestjs/microservices';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Timestamp } from 'typeorm';
import { MessageDecoder } from '@airframes/acars-decoder/dist/MessageDecoder';
import { EventsGateway } from '../events/events.gateway';
import { Message} from '../entities/message.entity';
import { MessageDecoding } from 'src/entities/message_decoding.entity';
@Injectable()
@Controller()
export class NatsController {
constructor(
private readonly eventsGateway: EventsGateway,
@InjectRepository(Message) private readonly messageRepository: Repository<Message>,
@InjectRepository(MessageDecoding) private readonly messageDecodingRepository: Repository<MessageDecoding>,
) {}
private readonly logger = new Logger(NatsController.name);
@EventPattern('message.created')
async handleMessageCreated(data: Record<string, unknown>) {
const eventReceivedTime = Date.now();
this.logger.log(`Received Message created event from NATS - Message: #${data.id}, Current Time: ${eventReceivedTime}`);
const message: Message = await this.messageRepository.findOne({
relations: ['station', 'airframe', 'flight'],
where: { id: data.id }
});
const meetingFoundTime = Date.now();
let secondsSinceEventReceived = (meetingFoundTime - eventReceivedTime) / 1000;
const messageTime = Date.parse(message.createdAt.toUTCString());
const delay = meetingFoundTime - messageTime;
const delayInSeconds = delay / 1000;
this.logger.log(`Retrieved Message from DB - Message: #${message.id}, Current Time: ${meetingFoundTime}, Message Time: ${messageTime}, Time since Event Received: ${secondsSinceEventReceived} seconds, Delay since Message create: ${delayInSeconds} seconds`);
await this.eventsGateway.broadcast('newMessages', [message]);
const broadcastedTime = Date.now();
secondsSinceEventReceived = (broadcastedTime - eventReceivedTime) / 1000;
this.logger.log(`Broadcasting Message to browsers - Message: #${message.id}, Current Time: ${broadcastedTime}, Time since Event Received: ${secondsSinceEventReceived} seconds`);
const decoding = new MessageDecoder().decode(message, { debug: { only_decoded: false } });
if (decoding.decoded == true) {
const messageDecoding = new MessageDecoding();
messageDecoding.message = message;
messageDecoding.decoderName = 'acars-decoder-typescript';
messageDecoding.decoderVersion = '1.0.28';
messageDecoding.decoderType = decoding.decoder.type;
messageDecoding.decoderPlugin = decoding.decoder.name;
messageDecoding.decodeLevel = decoding.decoder.decodeLevel;
messageDecoding.resultRaw = decoding.raw;
messageDecoding.resultFormatted = decoding.formatted;
messageDecoding.remainingUndecoded = decoding.remaining;
await this.messageDecodingRepository.save(messageDecoding);
this.logger.log(`Saved message decoding (#${messageDecoding.id})`);
}
}
}
|
kevinelliott/acars-backend
|
src/entities/report_monthly_count.entity.ts
|
<gh_stars>1-10
import {
Column,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('report_monthly_counts')
export class ReportMonthlyCount {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'station_id' })
stationId: number;
@Column({ name: 'date' })
date: Date;
@Column({ name: 'messages_count' })
messagesCount: number;
}
|
kevinelliott/acars-backend
|
src/entities/report_hourly_count.entity.ts
|
import {
Column,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('report_hourly_counts')
export class ReportHourlyCount {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'station_id' })
stationId: number;
@Column({ name: 'hour' })
hour: Date;
@Column({ name: 'messages_count' })
messagesCount: number;
}
|
kevinelliott/acars-backend
|
src/admin/geojson/admin_geo_json.module.ts
|
<filename>src/admin/geojson/admin_geo_json.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AdminGeoJsonController } from './admin_geo_json.controller';
import { AdminGeoJsonService } from './admin_geo_json.service';
import { Message } from '../../entities/message.entity';
import { Station } from '../../entities/station.entity';
@Module({
imports: [
TypeOrmModule.forFeature([Message], 'default'),
TypeOrmModule.forFeature([Station], 'default'),
],
controllers: [AdminGeoJsonController],
providers: [AdminGeoJsonService],
})
export class AdminGeoJsonModule {}
|
kevinelliott/acars-backend
|
src/entities/message_decoding.entity.ts
|
import {
Entity,
Column,
ColumnType,
CreateDateColumn,
UpdateDateColumn,
PrimaryGeneratedColumn,
ManyToOne,
JoinColumn
} from 'typeorm';
import { Message } from './message.entity';
@Entity('message_decodings')
export class MessageDecoding {
@PrimaryGeneratedColumn('uuid')
id: string;
@ManyToOne(type => Message, message => message.message_decodings)
@JoinColumn({ name: 'message_id' })
message: Message;
@Column({ name: 'decoder_name' })
decoderName: string;
@Column({ name: 'decoder_version' })
decoderVersion: string;
@Column({ name: 'decoder_type' })
decoderType: string;
@Column({ name: 'decoder_plugin' })
decoderPlugin: string;
@Column({ name: 'decode_level' })
decodeLevel: string;
@Column({ name: 'result_raw', type: 'jsonb' })
resultRaw: any;
@Column({ name: 'result_formatted', type: 'jsonb' })
resultFormatted: any;
@Column({ name: 'remaining_undecoded', type: 'jsonb' })
remainingUndecoded: any;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}
|
kevinelliott/acars-backend
|
src/main.ts
|
<filename>src/main.ts
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
require('newrelic');
import { configService } from './config/config.service';
import { AppModule } from './app.module';
async function bootstrap() {
const fs = require('fs');
let app;
// if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod') {
// const keyFile = fs.readFileSync('/certs/api.airframes.io-key.pem');
// const certFile = fs.readFileSync('/certs/api.airframes.io-cert.pem');
// app = await NestFactory.create(AppModule, {
// httpsOptions: {
// key: keyFile,
// cert: certFile,
// }
// });
// } else {
app = await NestFactory.create(AppModule, {});
// }
const eventsMicroservice = app.connectMicroservice({
transport: Transport.TCP,
});
const natsMicroservice = app.connectMicroservice({
transport: Transport.NATS,
options: {
url: configService.getNatsConfig().natsUrl,
},
});
await app.startAllMicroservicesAsync();
const allowedOrigins = "*:*"
const corsOptions = {
"origins": allowedOrigins,
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204,
"credentials": true
}
app.enableCors(corsOptions);
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod') {
await app.listen(80);
} else {
await app.listen(3001);
}
}
bootstrap();
|
kevinelliott/acars-backend
|
src/admin/geojson/admin_geo_json.controller.ts
|
import { Controller, Get, Param } from '@nestjs/common';
import { AdminGeoJsonService } from './admin_geo_json.service';
@Controller('admin/geojson')
export class AdminGeoJsonController {
constructor(private readonly adminGeoJsonService: AdminGeoJsonService) {}
@Get('frequencies')
getFrequencies(): Promise<Object> {
return this.adminGeoJsonService.getFrequencies();
}
}
|
kevinelliott/acars-backend
|
src/leaderboard/leaderboard.controller.ts
|
import { Controller, Get, Param } from '@nestjs/common';
import { LeaderboardService } from './leaderboard.service';
@Controller('leaderboard')
export class LeaderboardController {
constructor(private readonly leaderboardService: LeaderboardService) {}
@Get('current')
async current(@Param() params): Promise<Object> {
console.log('API: Getting current leaderboard');
return this.leaderboardService.getCurrentLeaderboard();
}
@Get(':date')
async specific(@Param() params): Promise<Object> {
console.log(`API: Getting a specific leaderboard: ${params.date}`);
const year = Number(params.date.substring(0, 4));
const month = Number(params.date.substring(4, 6)) - 1;
const date = new Date(year, month, 1);
return this.leaderboardService.getLeaderboardForDate(date);
}
}
|
kevinelliott/acars-backend
|
src/messages/messages.controller.ts
|
<filename>src/messages/messages.controller.ts
import { Controller, Get, Param, Query, UseInterceptors } from '@nestjs/common';
import { MessagesService } from './messages.service';
@Controller('messages')
export class MessagesController {
constructor(private readonly messagesService: MessagesService) {}
@Get()
findAll(@Query() params): Promise<Object> {
console.log('API: Getting all messages');
return this.messagesService.getMessages(params);
}
@Get(':id')
findOne(@Param() params): Promise<Object> {
console.log(`API: Getting message ${params.id}`);
return this.messagesService.getMessage(params.id);
}
}
|
kevinelliott/acars-backend
|
src/schedule/schedule.service.ts
|
import { Injectable, Logger, Inject } from '@nestjs/common';
import { Cron, Interval, Timeout, NestSchedule } from 'nest-schedule';
import { InjectRepository, InjectConnection } from '@nestjs/typeorm';
import { Connection, Repository, Timestamp } from 'typeorm';
import { EventsGateway } from '../events/events.gateway';
import { Flight } from '../entities/flight.entity';
import { Leaderboard } from '../entities/leaderboard.entity';
import { LeaderboardRank } from '../entities/leaderboard_rank.entity';
import { Message } from '../entities/message.entity';
import { Station } from '../entities/station.entity';
@Injectable() // Only support SINGLETON scope
export class ScheduleService extends NestSchedule {
constructor(
@Inject("EventsGateway") private readonly eventsGateway: EventsGateway,
@InjectConnection() private readonly connection: Connection,
@InjectRepository(Leaderboard) private readonly leaderboardRepository: Repository<Leaderboard>,
@InjectRepository(LeaderboardRank) private readonly leaderboardRankRepository: Repository<LeaderboardRank>,
@InjectRepository(Flight) private readonly flightRepository: Repository<Flight>,
@InjectRepository(Message) private readonly messageRepository: Repository<Message>,
@InjectRepository(Station) private readonly stationRepository: Repository<Station>,
) {
super()
}
private readonly logger = new Logger(ScheduleService.name);
// @Cron('0 0 2 * *', {
// startTime: new Date(),
// endTime: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
// })
// async cronJob() {
// console.log('executing cron job');
// }
// @Timeout(5000)
// onceJob() {
// console.log('executing once job');
// }
// @Cron('0 0 0 2 * *', {
// startTime: new Date(),
// endTime: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
// })
@Cron('0 */15 * * * *')
async calculateLeaderboard() {
this.logger.log('Cron Job: Calculating Leaderboard');
let date = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
await this.calculateLeaderboardForDate(date);
}
async calculateLeaderboardForDate(date) {
const dateString = date.toDateString();
await this.connection.transaction(async transactionalEntityManager => {
try {
// let leaderboard = await this.leaderboardRepository.findOne({
// relations: ['ranks', 'ranks.station'],
// where: {
// date: date
// }
// });
// this.logger.log(leaderboard);
// if (!leaderboard) {
let leaderboard = new Leaderboard();
leaderboard.date = date;
await this.leaderboardRepository.save(leaderboard);
// }
// Gather stations
let stations = await this.stationRepository.find({
relations: ['stationMessageCount']
});
// Gather airframe counts
let airframeAllTimeCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(DISTINCT airframe_id)', 'airframe_count')
.where("station_id IS NOT NULL")
.groupBy('station_id')
.orderBy('airframe_count', 'DESC')
.getRawMany();
let airframeThisMonthCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(DISTINCT airframe_id)', 'airframe_count')
.where(`station_id IS NOT NULL AND created_at >= DATE_TRUNC('month', DATE('${dateString}')) AND created_at < DATE_TRUNC('month', DATE('${dateString}') + INTERVAL '1 month')`)
.groupBy('station_id')
.orderBy('airframe_count', 'DESC')
.getRawMany();
let airframeLast24HoursCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(DISTINCT airframe_id)', 'airframe_count')
.where(`station_id IS NOT NULL AND created_at >= NOW() - INTERVAL '1 day'`)
.groupBy('station_id')
.orderBy('airframe_count', 'DESC')
.getRawMany();
// Gather flight counts
let flightAllTimeCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(DISTINCT flight_id)', 'flight_count')
.where("station_id IS NOT NULL")
.groupBy('station_id')
.orderBy('flight_count', 'DESC')
.getRawMany();
let flightThisMonthCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(DISTINCT flight_id)', 'flight_count')
.where(`station_id IS NOT NULL AND created_at >= DATE_TRUNC('month', DATE('${dateString}')) AND created_at < DATE_TRUNC('month', DATE('${dateString}') + INTERVAL '1 month')`)
.groupBy('station_id')
.orderBy('flight_count', 'DESC')
.getRawMany();
let flightLast24HoursCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(DISTINCT flight_id)', 'flight_count')
.where(`station_id IS NOT NULL AND created_at >= NOW() - INTERVAL '1 day'`)
.groupBy('station_id')
.orderBy('flight_count', 'DESC')
.getRawMany();
// Gather ground station counts
// Gather message counts
let messageThisMonthCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(*)', 'message_count')
.where(`station_id IS NOT NULL AND created_at >= DATE_TRUNC('month', DATE('${dateString}')) AND created_at < DATE_TRUNC('month', DATE('${dateString}') + INTERVAL '1 month')`)
.groupBy('station_id')
.orderBy('message_count', 'DESC')
.getRawMany();
let messageLast24HoursCounts = await this.messageRepository.createQueryBuilder("message")
.select('station_id', 'station_id')
.addSelect('COUNT(*)', 'message_count')
.where(`station_id IS NOT NULL AND created_at >= NOW() - INTERVAL '1 day'`)
.groupBy('station_id')
.orderBy('message_count', 'DESC')
.getRawMany();
let stationStats = [];
stations.forEach((station) => {
let stationStat = {};
stationStat['station'] = station;
let airframeAllTimeCount = airframeAllTimeCounts.find((count) => count.station_id == station.id);
if (airframeAllTimeCount) {
stationStat['airframeAllTimeCount'] = Number(airframeAllTimeCount.airframe_count);
} else {
stationStat['airframeAllTimeCount'] = 0;
}
let airframeThisMonthCount = airframeThisMonthCounts.find((count) => count.station_id == station.id);
if (airframeThisMonthCount) {
stationStat['airframeThisMonthCount'] = Number(airframeThisMonthCount.airframe_count);
} else {
stationStat['airframeThisMonthCount'] = 0;
}
let airframeLast24HoursCount = airframeLast24HoursCounts.find((count) => count.station_id == station.id);
if (airframeLast24HoursCount) {
stationStat['airframeLast24HoursCount'] = Number(airframeLast24HoursCount.airframe_count);
} else {
stationStat['airframeLast24HoursCount'] = 0;
}
let flightAllTimeCount = flightAllTimeCounts.find((count) => count.station_id == station.id);
if (flightAllTimeCount) {
stationStat['flightAllTimeCount'] = Number(flightAllTimeCount.flight_count);
} else {
stationStat['flightAllTimeCount'] = 0;
}
let flightThisMonthCount = flightThisMonthCounts.find((count) => count.station_id == station.id);
if (flightThisMonthCount) {
stationStat['flightThisMonthCount'] = Number(flightThisMonthCount.flight_count);
} else {
stationStat['flightThisMonthCount'] = 0;
}
let flightLast24HoursCount = flightLast24HoursCounts.find((count) => count.station_id == station.id);
if (flightLast24HoursCount) {
stationStat['flightLast24HoursCount'] = Number(flightLast24HoursCount.flight_count);
} else {
stationStat['flightLast24HoursCount'] = 0;
}
if (station.stationMessageCount) {
stationStat['messageAllTimeCount'] = Number(station.stationMessageCount.messagesCount);
} else {
stationStat['messageAllTimeCount'] = 0;
}
let messageThisMonthCount = messageThisMonthCounts.find((count) => count.station_id == station.id);
if (messageThisMonthCount) {
stationStat['messageThisMonthCount'] = Number(messageThisMonthCount.message_count);
} else {
stationStat['messageThisMonthCount'] = 0;
}
let messageLast24HoursCount = messageLast24HoursCounts.find((count) => count.station_id == station.id);
if (messageLast24HoursCount) {
stationStat['messageLast24HoursCount'] = Number(messageLast24HoursCount.message_count);
} else {
stationStat['messageLast24HoursCount'] = 0;
}
stationStat['points'] = (
Math.round(stationStat['messageAllTimeCount'] * 0.05) +
(stationStat['messageThisMonthCount'] * 1) +
(stationStat['messageLast24HoursCount'] * 2) +
(stationStat['airframeAllTimeCount'] * 5) +
(stationStat['airframeThisMonthCount'] * 10) +
(stationStat['airframeLast24HoursCount'] * 50) +
Math.round(stationStat['flightAllTimeCount'] * 0.20) +
(stationStat['flightThisMonthCount'] * 10) +
(stationStat['flightLast24HoursCount'] * 50)
);
stationStats.push(stationStat);
});
stationStats.sort((a, b) => (a.points > b.points) ? 1 : -1).reverse();
stationStats = stationStats.map((station, index) => {
station.rank = index + 1;
return station;
});
await this.leaderboardRankRepository.createQueryBuilder()
.delete()
.from(LeaderboardRank)
.where("leaderboard_id = :id", { id: leaderboard.id })
.execute();
stationStats.forEach(async (stationStat) => {
// console.log(stationStat);
if (stationStat.station && stationStat.station.id) {
let rank = new LeaderboardRank();
rank.leaderboard = leaderboard;
rank.station = stationStat.station;
rank.ranking = stationStat.rank;
rank.points = stationStat.points;
rank.airframeAllTimeCount = stationStat.airframeAllTimeCount;
rank.airframeThisMonthCount = stationStat.airframeThisMonthCount;
rank.airframeLast24HoursCount = stationStat.airframeLast24HoursCount;
rank.flightAllTimeCount = stationStat.flightAllTimeCount;
rank.flightThisMonthCount = stationStat.flightThisMonthCount;
rank.flightLast24HoursCount = stationStat.flightLast24HoursCount;
rank.messageAllTimeCount = stationStat.messageAllTimeCount;
rank.messageThisMonthCount = stationStat.messageThisMonthCount;
rank.messageLast24HoursCount = stationStat.messageLast24HoursCount;
await this.leaderboardRankRepository.save(rank);
}
});
await this.leaderboardRepository.save(leaderboard);
}
finally {
}
});
}
@Interval(5000)
async intervalJob() {
// this.logger.log('Job running to gather and broadcast updated data.');
// this.eventsGateway.broadcast('events', 'interval-job');
let stations = await this.stationRepository.find({
relations: ['stationMessageCount']
});
// this.logger.log('Preparing to broadcast ' + stations.length + ' stations.');
this.eventsGateway.broadcast('stations', stations);
// Update inactive flights
await this.flightRepository
.createQueryBuilder()
.update(Flight)
.set({ status: 'radio-silence' })
.where("status = :status AND updated_at <= (timezone('utc', now()) - interval '5 minutes')", { status: 'in-flight' })
.execute();
let activeFlights = await this.flightRepository.find({
relations: ['airframe'],
where: { status: 'in-flight' }
});
// this.logger.log('Preparing to broadcast ' + activeFlights.length + ' active flights.');
this.eventsGateway.broadcast('activeFlights', activeFlights);
// if you want to cancel the job, you should return true;
// return true;
}
}
|
kevinelliott/acars-backend
|
src/airframes/airframes.controller.ts
|
<filename>src/airframes/airframes.controller.ts<gh_stars>1-10
import { Controller, Get, Param } from '@nestjs/common';
import { AirframesService } from './airframes.service';
@Controller('airframes')
export class AirframesController {
constructor(private readonly airframesService: AirframesService) {}
@Get()
async findAll(@Param() params): Promise<Object> {
console.log('Getting all airframes');
return this.airframesService.getAllAirframes();
}
@Get(':id')
async findOne(@Param() params): Promise<Object> {
console.log(params.id);
return this.airframesService.getAirframe(params.id);
}
}
|
kevinelliott/acars-backend
|
src/admin/geojson/admin_geo_json.service.ts
|
<reponame>kevinelliott/acars-backend<gh_stars>1-10
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from '../../entities/message.entity';
import { Station } from '../../entities/station.entity';
@Injectable()
export class AdminGeoJsonService {
constructor(
@InjectRepository(Message, 'default') private readonly messageRepository: Repository<Message>,
@InjectRepository(Station, 'default') private readonly stationRepository: Repository<Station>,
) { }
async getFrequencies(): Promise<Object> {
console.log('blah');
const stations: any = await this.getStations();
console.log(stations);
const features = await Promise.all(stations.map(async (station: Station) => {
console.log(station);
const messages: any = await this.messageRepository.createQueryBuilder('message')
.select('frequency', 'frequency')
.addSelect('count(*)', 'message_count')
.where(`station_id = ${station.id}`)
.where("created_at > now() - interval '30 days'")
.groupBy('frequency')
.orderBy('message_count', 'DESC')
.getRawMany();
const counts = messages.map((message: any) => {
const frequency = message.frequency != null ? message.frequency.toFixed(3) : 'UNKNOWN';
return `${frequency} had ${message.message_count} messages`
});
const tooltip = `LAST 30 DAYS\n${counts.join('\n')}`;
var min = 0.0200,
max = 0.50,
randNumber = Math.random() * (max - min) + min;
const point = {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [(Number(station.longitude) + randNumber).toFixed(2), (Number(station.latitude) + randNumber).toFixed(2)]
},
properties: {
name: station.ident,
tooltip: tooltip
}
};
// features.push(point);
return point;
}));
return { type: 'FeatureCollection', features: features };
}
async getStations(): Promise<Object> {
const stations: Array<Station> = await this.stationRepository.createQueryBuilder('stations')
.orderBy('ident', 'ASC')
.where('stations.latitude IS NOT NULL')
.getMany();
return stations;
}
}
|
kevinelliott/acars-backend
|
src/user/user.service.ts
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Station } from '../entities/station.entity';
@Injectable()
export class UserService {
constructor(
@InjectRepository(Station, 'readonly') private readonly stationRepository: Repository<Station>,
) { }
async myIp(ip: string): Promise<Object> {
const data = {
ipAddress: ip,
stations: []
};
data.stations = await this.stationRepository.find({
where: { ipAddress: ip }
});
return data;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.