Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support apiId(Multiple cloudformation stacks) #597

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions doc/general-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ appSync:
- `logging`: See [Logging](#Logging)
- `xrayEnabled`: Boolean. Enable or disable X-Ray tracing.
- `tags`: A key-value pair for tagging this AppSync API
- `apiId`: See [ApiId](#ApiId)

## Schema

Expand Down Expand Up @@ -185,3 +186,33 @@ appSync:
- `excludeVerboseContent`: Boolean, Optional. Exclude or not verbose content (headers, response headers, context, and evaluated mapping templates), regardless of field logging level. Defaults to `false`.
- `retentionInDays`: Optional. Number of days to retain the logs. Defaults to [`provider.logRetentionInDays`](https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml#general-function-settings).
- `roleArn`: Optional. The role ARN to use for AppSync to write into CloudWatch. If not specified, a new role is created by default.


## ApiId
If you want to manage your existing AppSync Api through the serverless, you can specify `apiId.`
This is handy if you
- defined your API in the AWS console
- defined your API through the cloudformation in the current or another stack

To point your resources into existing AppSync API, you must provide apiId, which can be a string or imported value from another stack.
```yaml
appSync:
name: my-api
apiId: "existing api id"
```

The following configuration options are only associated with the creation of a new AppSync endpoint and will be ignored if you provide the apiId parameter:
- name
- authentication
- additionalAuthentications
- schema
- domain
- apiKeys
- xrayEnabled
- logging
- waf
- Tags
> Note: you should never specify this parameter if you're managing your AppSync through this plugin since it results in removing your API.

### Schema
After specifying this parameter, you need to manually keep your schema up to date or from the main stack where your root AppSync API is defined. The plugin is not taking into account schema property due to AppSync limitation and inability to merge schemas across multiple stacks
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This whole section is confusing and probably not necessary.

Instead, we should add clear guidelines on how and why you should use the apiId parameters.
A bit like described here for API Gateway.

52 changes: 52 additions & 0 deletions src/__tests__/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ describe('Api', () => {
expect(api.compileEndpoint()).toMatchSnapshot();
expect(api.functions).toMatchSnapshot();
});
it('should not compile the Api Resource when apiId is provided', () => {
const api = new Api(given.appSyncConfig({ apiId: '123' }), plugin);
expect(api.compileEndpoint()).toMatchInlineSnapshot(`Object {}`);
});
});

describe('Logs', () => {
Expand All @@ -239,6 +243,13 @@ describe('Api', () => {
);
});

it('should not compile CloudWatch Resources when apiId is provided', () => {
const api = new Api(given.appSyncConfig({ apiId: '1234' }), plugin);
expect(api.compileCloudWatchLogGroup()).toMatchInlineSnapshot(
`Object {}`,
);
});

it('should compile CloudWatch Resources when enaabled', () => {
const api = new Api(
given.appSyncConfig({
Expand Down Expand Up @@ -465,6 +476,20 @@ describe('Api', () => {
}
`);
});
it('should not generate an api key resources when apiId is provided', () => {
const api = new Api(
given.appSyncConfig({
apiId: '1234',
}),
plugin,
);
expect(
api.compileApiKey({
name: 'Default',
description: 'Default Key',
}),
).toMatchInlineSnapshot(`Object {}`);
});
});

describe('LambdaAuthorizer', () => {
Expand All @@ -482,6 +507,18 @@ describe('Api', () => {
);
});

it('should not generate the Lambda Authorizer Resources when apiId is provided', () => {
const api = new Api(
given.appSyncConfig({
apiId: '123',
}),
plugin,
);
expect(api.compileLambdaAuthorizerPermission()).toMatchInlineSnapshot(
`Object {}`,
);
});

it('should generate the Lambda Authorizer Resources from basic auth', () => {
const api = new Api(
given.appSyncConfig({
Expand Down Expand Up @@ -560,6 +597,11 @@ describe('Caching', () => {
expect(api.compileCachingResources()).toEqual({});
});

it('should not generate Resources when apiId is provided', () => {
const api = new Api(given.appSyncConfig({ apiId: '1234' }), plugin);
expect(api.compileCachingResources()).toEqual({});
});

it('should generate Resources with defaults', () => {
const api = new Api(
given.appSyncConfig({
Expand Down Expand Up @@ -723,4 +765,14 @@ describe('Domains', () => {
);
expect(api.compileCustomDomain()).toMatchSnapshot();
});

it('should not generate domain resources when apiId is provided', () => {
const api = new Api(
given.appSyncConfig({
apiId: '123',
}),
plugin,
);
expect(api.compileCustomDomain()).toMatchInlineSnapshot(`Object {}`);
});
});
11 changes: 11 additions & 0 deletions src/__tests__/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ describe('schema', () => {
`);
});

it('should generate a schema resource if apiId is provided', () => {
const api = new Api(
given.appSyncConfig({
apiId: '123',
}),
plugin,
);

expect(api.compileSchema()).toMatchInlineSnapshot(`Object {}`);
});

it('should merge the schemas', () => {
const api = new Api(given.appSyncConfig(), plugin);
const schema = new Schema(api, [
Expand Down
1 change: 0 additions & 1 deletion src/__tests__/validation/__snapshots__/base.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,5 @@ exports[`Valdiation Waf Invalid should validate a Throttle limit 1`] = `

exports[`Valdiation should validate 1`] = `
": must have required property 'name'
: must have required property 'authentication'
/unknownPorp: invalid (unknown) property"
`;
14 changes: 14 additions & 0 deletions src/__tests__/waf.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,20 @@ describe('Waf', () => {
});
expect(waf.compile()).toMatchSnapshot();
});

it('should not generate waf Resources if api id is provided', () => {
const api = new Api(
given.appSyncConfig({
waf: {
enabled: false,
name: 'Waf',
rules: [],
},
}),
plugin,
);
expect(api.compileWafRules()).toEqual({});
});
});

describe('Throttle rules', () => {
Expand Down
4 changes: 2 additions & 2 deletions src/getAppSyncConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export const getAppSyncConfig = (config: AppSyncConfigInput): AppSyncConfig => {
const dataSources: Record<string, DataSourceConfig> = {};
const resolvers: Record<string, ResolverConfig> = {};
const pipelineFunctions: Record<string, PipelineFunctionConfig> = {};
const additionalAuthentications = config.additionalAuthentications || [];

forEach(flattenMaps(config.dataSources), (ds, name) => {
dataSources[name] = {
Expand Down Expand Up @@ -163,11 +164,10 @@ export const getAppSyncConfig = (config: AppSyncConfigInput): AppSyncConfig => {
};
});

const additionalAuthentications = config.additionalAuthentications || [];

let apiKeys: Record<string, ApiKeyConfig> | undefined;
if (
config.authentication.type === 'API_KEY' ||
config.authentication?.type === 'API_KEY' ||
additionalAuthentications.some((auth) => auth.type === 'API_KEY')
) {
const inputKeys = config.apiKeys || [];
Expand Down
27 changes: 24 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import {
ListCertificatesResponse,
} from 'aws-sdk/clients/acm';
import terminalLink from 'terminal-link';
import { AppSyncConfig } from './types/plugin';

const CONSOLE_BASE_URL = 'https://console.aws.amazon.com';

Expand All @@ -86,6 +87,7 @@ class ServerlessAppsyncPlugin {
public readonly configurationVariablesSources?: VariablesSourcesDefinition;
private api?: Api;
private naming?: Naming;
private config?: AppSyncConfig;

constructor(
public serverless: Serverless,
Expand Down Expand Up @@ -347,6 +349,11 @@ class ServerlessAppsyncPlugin {
async getApiId() {
this.loadConfig();

if (this.config?.apiId) {
return this.config.apiId;
}


if (!this.naming) {
throw new this.serverless.classes.Error(
'Could not find the naming service. This should not happen.',
Expand Down Expand Up @@ -377,6 +384,10 @@ class ServerlessAppsyncPlugin {
async gatherData() {
const apiId = await this.getApiId();

if (typeof apiId !== 'string') {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (typeof apiId !== 'string') {
if (!apiId) {

if for some reason, apiId is an empty string, it probably does not make sense to continue either.

return;
}

const { graphqlApi } = await this.provider.request<
GetGraphqlApiRequest,
GetGraphqlApiResponse
Expand Down Expand Up @@ -410,6 +421,10 @@ class ServerlessAppsyncPlugin {
async getIntrospection() {
const apiId = await this.getApiId();

if (typeof apiId !== 'string') {
return;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just returning is probably not good enough.
I would show a warning.

In fact I would probably not allow calling any of these commands (assoc domain, etc) from a "child" service stack.

Please call this command from the service where the AppSync API is created.

}

const { schema } = await this.provider.request<
GetIntrospectionSchemaRequest,
GetIntrospectionSchemaResponse
Expand Down Expand Up @@ -673,10 +688,16 @@ class ServerlessAppsyncPlugin {
}

async assocDomain() {
const domain = this.getDomain();
const apiId = await this.getApiId();

if (typeof apiId !== 'string') {
return;
}

const domain = this.getDomain();
const assoc = await this.getApiAssocStatus(domain.name);


if (assoc?.associationStatus !== 'NOT_FOUND' && assoc?.apiId !== apiId) {
log.warning(
`The domain ${domain.name} is currently associated to another API (${assoc?.apiId})`,
Expand Down Expand Up @@ -957,9 +978,9 @@ class ServerlessAppsyncPlugin {
throw error;
}
}
const config = getAppSyncConfig(appSync);
this.config = getAppSyncConfig(appSync);
this.naming = new Naming(appSync.name);
this.api = new Api(config, this);
this.api = new Api(this.config, this);
}

validateSchemas() {
Expand Down
Loading