Skip to content

Commit

Permalink
chore: sync console-preview with next/main (#12238)
Browse files Browse the repository at this point in the history
  • Loading branch information
HuiSF authored Oct 9, 2023
2 parents d807e55 + 1ffc046 commit 5f040a2
Show file tree
Hide file tree
Showing 111 changed files with 584 additions and 365 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/push-integ-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ concurrency:
on:
push:
branches:
- feat/example-integ-test-branch/main
- next/main

jobs:
e2e:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Hub } from '@aws-amplify/core';
import { record as pinpointRecord } from '@aws-amplify/core/internals/providers/pinpoint';
import { ConsoleLogger as Logger } from '@aws-amplify/core/internals/utils';
import { record } from '../../../../src/providers/pinpoint';
Expand All @@ -20,35 +21,43 @@ import {
config,
} from './testUtils/data';

jest.mock('@aws-amplify/core');
jest.mock('@aws-amplify/core/internals/providers/pinpoint');
jest.mock('../../../../src/utils');
jest.mock('../../../../src/providers/pinpoint/utils');
jest.mock('@aws-amplify/core/internals/providers/pinpoint');

describe('Pinpoint API: record', () => {
// create spies
const loggerWarnSpy = jest.spyOn(Logger.prototype, 'warn');
// create mocks
const mockPinpointRecord = pinpointRecord as jest.Mock;
const mockResolveConfig = resolveConfig as jest.Mock;
const mockResolveCredentials = resolveCredentials as jest.Mock;
const mockIsAnalyticsEnabled = isAnalyticsEnabled as jest.Mock;
const mockGetAnalyticsUserAgentString =
getAnalyticsUserAgentString as jest.Mock;
const loggerWarnSpy = jest.spyOn(Logger.prototype, 'warn');
const mockHubDispatch = Hub.dispatch as jest.Mock;

beforeEach(() => {
mockPinpointRecord.mockReset();
mockPinpointRecord.mockResolvedValue(undefined);
mockResolveConfig.mockReset();
mockResolveConfig.mockReturnValue(config);
mockIsAnalyticsEnabled.mockReset();
mockIsAnalyticsEnabled.mockReturnValue(true);
mockGetAnalyticsUserAgentString.mockReset();
mockGetAnalyticsUserAgentString.mockReturnValue('mock-user-agent');
mockResolveCredentials.mockReset();
mockResolveCredentials.mockResolvedValue({
credentials,
identityId,
});
});

afterEach(() => {
mockPinpointRecord.mockReset();
mockResolveConfig.mockReset();
mockIsAnalyticsEnabled.mockReset();
mockGetAnalyticsUserAgentString.mockReset();
mockResolveCredentials.mockReset();
mockHubDispatch.mockClear();
});

it('invokes the core record implementation', async () => {
record(event);

Expand Down Expand Up @@ -101,4 +110,17 @@ describe('Pinpoint API: record', () => {

expect(mockPinpointRecord).not.toBeCalled();
});

it('should dispatch a Hub event', async () => {
record(event);

await new Promise(process.nextTick);

expect(mockHubDispatch).toBeCalledWith(
'analytics',
{ event: 'record', data: event, message: 'Recording Analytics event' },
'Analytics',
expect.anything()
);
});
});
8 changes: 8 additions & 0 deletions packages/analytics/src/providers/pinpoint/apis/record.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import { Hub } from '@aws-amplify/core';
import {
AMPLIFY_SYMBOL,
AnalyticsAction,
ConsoleLogger as Logger,
} from '@aws-amplify/core/internals/utils';
Expand Down Expand Up @@ -59,6 +61,12 @@ export const record = (input: RecordInput): void => {

resolveCredentials()
.then(({ credentials, identityId }) => {
Hub.dispatch(
'analytics',
{ event: 'record', data: input, message: 'Recording Analytics event' },
'Analytics',
AMPLIFY_SYMBOL
);
recordCore({
appId,
category: 'Analytics',
Expand Down
7 changes: 6 additions & 1 deletion packages/api-graphql/__tests__/v6-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ import {
} from './utils/expects';

import {
__amplify,
GraphQLResult,
GraphqlSubscriptionResult,
GraphqlSubscriptionMessage,
GraphQLQuery,
GraphQLSubscription,
GraphQLReturnType,
V6Client,
} from '../src/types';

import {
Expand All @@ -44,7 +46,10 @@ const serverManagedFields = {

describe('client', () => {
// `generateClient()` is only exported from top-level API category.
const client = { graphql };
const client = {
[__amplify]: Amplify,
graphql,
} as V6Client;

beforeEach(() => {
Amplify.configure({
Expand Down
4 changes: 3 additions & 1 deletion packages/api-graphql/src/GraphQLAPI.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { AmplifyClassV6 } from '@aws-amplify/core';
import { GraphQLOptions, GraphQLResult } from './types';
import { InternalGraphQLAPIClass } from './internals';
import { Observable } from 'rxjs';
Expand Down Expand Up @@ -30,10 +31,11 @@ export class GraphQLAPIClass extends InternalGraphQLAPIClass {
* @returns An Observable if the query is a subscription query, else a promise of the graphql result.
*/
graphql<T = any>(
amplify: AmplifyClassV6,
options: GraphQLOptions,
additionalHeaders?: { [key: string]: string }
): Observable<GraphQLResult<T>> | Promise<GraphQLResult<T>> {
return super.graphql(options, additionalHeaders);
return super.graphql(amplify, options, additionalHeaders);
}

/**
Expand Down
25 changes: 16 additions & 9 deletions packages/api-graphql/src/internals/InternalGraphQLAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
OperationTypeNode,
} from 'graphql';
import { Observable } from 'rxjs';
import { Amplify, Cache, fetchAuthSession } from '@aws-amplify/core';
import { AmplifyClassV6 } from '@aws-amplify/core';
import {
APIAuthMode,
CustomUserAgentDetails,
Expand Down Expand Up @@ -54,7 +54,6 @@ export class InternalGraphQLAPIClass {
private _options;
private appSyncRealTime: AWSAppSyncRealTimeProvider | null;

Cache = Cache;
private _api = { post, updateRequestToBeCancellable };

/**
Expand All @@ -71,10 +70,11 @@ export class InternalGraphQLAPIClass {
}

private async _headerBasedAuth(
amplify: AmplifyClassV6,
authMode: APIAuthMode,
additionalHeaders: { [key: string]: string } = {}
) {
const config = Amplify.getConfig();
const config = amplify.getConfig();
const {
region: region,
endpoint: appSyncGraphqlEndpoint,
Expand All @@ -95,7 +95,7 @@ export class InternalGraphQLAPIClass {
};
break;
case 'iam':
const session = await fetchAuthSession();
const session = await amplify.Auth.fetchAuthSession();
if (session.credentials === undefined) {
throw new Error(GraphQLAuthError.NO_CREDENTIALS);
}
Expand All @@ -105,7 +105,9 @@ export class InternalGraphQLAPIClass {
try {
let token;

token = (await fetchAuthSession()).tokens?.accessToken.toString();
token = (
await amplify.Auth.fetchAuthSession()
).tokens?.accessToken.toString();

if (!token) {
throw new Error(GraphQLAuthError.NO_FEDERATED_JWT);
Expand Down Expand Up @@ -158,6 +160,7 @@ export class InternalGraphQLAPIClass {
* @returns An Observable if the query is a subscription query, else a promise of the graphql result.
*/
graphql<T = any>(
amplify: AmplifyClassV6,
{ query: paramQuery, variables = {}, authMode, authToken }: GraphQLOptions,
additionalHeaders?: { [key: string]: string },
customUserAgentDetails?: CustomUserAgentDetails
Expand Down Expand Up @@ -185,6 +188,7 @@ export class InternalGraphQLAPIClass {
case 'mutation':
const abortController = new AbortController();
const responsePromise = this._graphql<T>(
amplify,
{ query, variables, authMode },
headers,
abortController,
Expand All @@ -197,6 +201,7 @@ export class InternalGraphQLAPIClass {
return responsePromise;
case 'subscription':
return this._graphqlSubscribe(
amplify,
{ query, variables, authMode },
headers,
customUserAgentDetails
Expand All @@ -207,12 +212,13 @@ export class InternalGraphQLAPIClass {
}

private async _graphql<T = any>(
amplify: AmplifyClassV6,
{ query, variables, authMode }: GraphQLOptions,
additionalHeaders = {},
abortController: AbortController,
customUserAgentDetails?: CustomUserAgentDetails
): Promise<GraphQLResult<T>> {
const config = Amplify.getConfig();
const config = amplify.getConfig();

const { region: region, endpoint: appSyncGraphqlEndpoint } =
config.API?.GraphQL || {};
Expand All @@ -223,10 +229,10 @@ export class InternalGraphQLAPIClass {
// TODO: Figure what we need to do to remove `!`'s.
const headers = {
...(!customGraphqlEndpoint &&
(await this._headerBasedAuth(authMode!, additionalHeaders))),
(await this._headerBasedAuth(amplify, authMode!, additionalHeaders))),
...((customGraphqlEndpoint &&
(customEndpointRegion
? await this._headerBasedAuth(authMode!, additionalHeaders)
? await this._headerBasedAuth(amplify, authMode!, additionalHeaders)
: { Authorization: null })) ||
{}),
...additionalHeaders,
Expand Down Expand Up @@ -311,11 +317,12 @@ export class InternalGraphQLAPIClass {
}

private _graphqlSubscribe(
amplify: AmplifyClassV6,
{ query, variables, authMode }: GraphQLOptions,
additionalHeaders = {},
customUserAgentDetails?: CustomUserAgentDetails
): Observable<any> {
const { GraphQL } = Amplify.getConfig().API ?? {};
const { GraphQL } = amplify.getConfig().API ?? {};
if (!this.appSyncRealTime) {
this.appSyncRealTime = new AWSAppSyncRealTimeProvider();
}
Expand Down
22 changes: 18 additions & 4 deletions packages/api-graphql/src/internals/v6.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { GraphQLAPI } from '../GraphQLAPI';
import { GraphQLOptionsV6, GraphQLResponseV6 } from '../types';
import {
__amplify,
V6Client,
GraphQLOptionsV6,
GraphQLResponseV6,
} from '../types';

/**
* Invokes graphql operations against a graphql service, providing correct input and
Expand Down Expand Up @@ -91,6 +96,7 @@ export function graphql<
FALLBACK_TYPES = unknown,
TYPED_GQL_STRING extends string = string
>(
this: V6Client,
options: GraphQLOptionsV6<FALLBACK_TYPES, TYPED_GQL_STRING>,
additionalHeaders?: { [key: string]: string }
): GraphQLResponseV6<FALLBACK_TYPES, TYPED_GQL_STRING> {
Expand All @@ -99,7 +105,11 @@ export function graphql<
* Neither of these can actually be validated at runtime. Hence, we don't perform
* any validation or type-guarding here.
*/
const result = GraphQLAPI.graphql(options, additionalHeaders);
const result = GraphQLAPI.graphql(
this[__amplify],
options,
additionalHeaders
);
return result as any;
}

Expand All @@ -108,7 +118,11 @@ export function graphql<
* @param {any} request - request to cancel
* @returns - A boolean indicating if the request was cancelled
*/
export function cancel(promise: Promise<any>, message?: string): boolean {
export function cancel(
this: V6Client,
promise: Promise<any>,
message?: string
): boolean {
return GraphQLAPI.cancel(promise, message);
}

Expand All @@ -117,7 +131,7 @@ export function cancel(promise: Promise<any>, message?: string): boolean {
* @param {any} error - Any error
* @returns - A boolean indicating if the error was from an api request cancellation
*/
export function isCancelError(error: any): boolean {
export function isCancelError(this: V6Client, error: any): boolean {
return GraphQLAPI.isCancelError(error);
}

Expand Down
24 changes: 24 additions & 0 deletions packages/api-graphql/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { AmplifyClassV6 } from '@aws-amplify/core';
import { Source, DocumentNode, GraphQLError } from 'graphql';
export { OperationTypeNode } from 'graphql';
import { Observable } from 'rxjs';
Expand Down Expand Up @@ -339,3 +340,26 @@ export type GeneratedSubscription<InputType, OutputType> = string & {
__generatedSubscriptionInput: InputType;
__generatedSubscriptionOutput: OutputType;
};

type FilteredKeys<T> = {
[P in keyof T]: T[P] extends never ? never : P;
}[keyof T];
type ExcludeNeverFields<O> = {
[K in FilteredKeys<O>]: O[K];
};

export const __amplify = Symbol('amplify');

export type V6Client<T extends Record<any, any> = never> = ExcludeNeverFields<{
[__amplify]: AmplifyClassV6;
graphql: <FALLBACK_TYPES = unknown, TYPED_GQL_STRING extends string = string>(
options: GraphQLOptionsV6<FALLBACK_TYPES, TYPED_GQL_STRING>,
additionalHeaders?:
| {
[key: string]: string;
}
| undefined
) => GraphQLResponseV6<FALLBACK_TYPES, TYPED_GQL_STRING>;
cancel: (promise: Promise<any>, message?: string) => boolean;
isCancelError: (error: any) => boolean;
}>;
13 changes: 0 additions & 13 deletions packages/api-rest/src/utils/index.native.ts

This file was deleted.

2 changes: 2 additions & 0 deletions packages/api-rest/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import './polyfills';

export { createCancellableOperation } from './createCancellableOperation';
export { resolveCredentials } from './resolveCredentials';
export { parseSigningInfo } from './parseSigningInfo';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

// no op
// noop - polyfills not required on platform
Loading

0 comments on commit 5f040a2

Please sign in to comment.