aws-sdk#CodeCommit TypeScript Examples
The following examples show how to use
aws-sdk#CodeCommit.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Delete)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<null> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
let { arn, id, name } = model;
if (!arn && !id && !name) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
}
if (!arn) {
arn = Resource.formatArn(region, awsAccountId, id);
}
if (!id) {
id = Resource.extractResourceId(arn);
}
const rules = await this.listRuleTemplates(service, args.logger, { id, name }).catch((err: AWSError) => {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
});
if (!rules.length) {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
}
name = rules[0].name;
const request: CodeCommit.DeleteApprovalRuleTemplateInput = {
approvalRuleTemplateName: name,
};
args.logger.log({ action, message: 'before invoke deleteApprovalRuleTemplate', request });
const response = await service.deleteApprovalRuleTemplate(request).promise();
args.logger.log({ action, message: 'after invoke deleteApprovalRuleTemplate', response });
args.logger.log({ action, message: 'done' });
return Promise.resolve(null);
}
Example #2
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Read)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async read(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { logicalResourceIdentifier } = args.request;
const { arn } = model;
if (!arn) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
}
const approvalRuleTemplateId = Resource.extractResourceId(arn);
const approvalRuleTemplate = await this.getRuleTemplate(service, args.logger, { id: approvalRuleTemplateId });
model.approvalRuleTemplateName = approvalRuleTemplate.approvalRuleTemplateName;
const result = await this.listRepositoryAssociations(service, args.logger, model);
if (!result.repositoryNames?.length) {
throw new exceptions.NotFound(this.typeName, model.approvalRuleTemplateName);
}
args.logger.log({ action, message: 'done', result });
return Promise.resolve(result);
}
Example #3
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Delete)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<null> {
const { logicalResourceIdentifier } = args.request;
const { arn } = model;
if (!arn) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
}
const approvalRuleTemplateId = Resource.extractResourceId(arn);
const approvalRuleTemplate = await this.getRuleTemplate(service, args.logger, { id: approvalRuleTemplateId });
model.approvalRuleTemplateName = approvalRuleTemplate.approvalRuleTemplateName;
const result = await this.listRepositoryAssociations(service, args.logger, model);
if (!result.repositoryNames?.length) {
throw new exceptions.NotFound(this.typeName, model.approvalRuleTemplateName);
}
const request: CodeCommit.BatchDisassociateApprovalRuleTemplateFromRepositoriesInput = {
approvalRuleTemplateName: model.approvalRuleTemplateName,
repositoryNames: result.repositoryNames,
};
args.logger.log({ action, message: 'before invoke batchDisassociateApprovalRuleTemplateFromRepositories', request });
const response = await service.batchDisassociateApprovalRuleTemplateFromRepositories(request).promise();
args.logger.log({ action, message: 'after invoke batchDisassociateApprovalRuleTemplateFromRepositories', response });
await this.checkBatchResponse(response, args.logger);
args.logger.log({ action, message: 'done' });
return Promise.resolve(null);
}
Example #4
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
private async listRepositoryAssociations(service: CodeCommit, logger: Logger, model: ResourceModel): Promise<ResourceModel> {
const request: CodeCommit.ListRepositoriesForApprovalRuleTemplateInput = {
approvalRuleTemplateName: model.approvalRuleTemplateName,
};
try {
logger.log({ message: 'before invoke listRepositoriesForApprovalRuleTemplate', request });
const response = await service.listRepositoriesForApprovalRuleTemplate(request).promise();
logger.log({ message: 'after invoke listRepositoriesForApprovalRuleTemplate', response });
const result = new ResourceModel();
result.approvalRuleTemplateArn = model.approvalRuleTemplateArn;
result.approvalRuleTemplateName = model.approvalRuleTemplateName;
result.repositoryNames = response.repositoryNames;
result.arn = model.arn;
return Promise.resolve(result);
} catch (err) {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound('ApprovalRuleTemplateName', model.approvalRuleTemplateName);
} else {
// Raise the original exception
throw err;
}
}
}
Example #5
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
private async getRuleTemplate(service: CodeCommit, logger: Logger, filter: Filter): Promise<CodeCommit.ApprovalRuleTemplate> {
logger.log({ message: 'before invoke listApprovalRuleTemplates' });
const response = await service.listApprovalRuleTemplates().promise();
logger.log({ message: 'after invoke listApprovalRuleTemplates', response });
const rules: CodeCommit.ApprovalRuleTemplate[] = [];
for (const approvalRuleTemplateName of response.approvalRuleTemplateNames) {
const request: CodeCommit.GetApprovalRuleTemplateInput = {
approvalRuleTemplateName,
};
logger.log({ message: 'before invoke getApprovalRuleTemplate', request });
const response = await service.getApprovalRuleTemplate(request).promise();
logger.log({ message: 'after invoke getApprovalRuleTemplate', response });
rules.push(response.approvalRuleTemplate || {});
}
const approvalRuleTemplate = rules.find((approvalRuleTemplate: CodeCommit.ApprovalRuleTemplate) => {
return (filter.id && filter.id === approvalRuleTemplate.approvalRuleTemplateId) || (filter.name && filter.name === approvalRuleTemplate.approvalRuleTemplateName);
});
if (!approvalRuleTemplate) {
throw new exceptions.NotFound('ApprovalRuleTemplate', filter.id || filter.name);
}
return Promise.resolve(approvalRuleTemplate);
}
Example #6
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Read)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async read(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
let { arn, id } = model;
const name = model.name;
if (!arn && !id && !name) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
}
if (!arn) {
arn = Resource.formatArn(region, awsAccountId, id);
}
if (!id) {
id = Resource.extractResourceId(arn);
}
try {
const rules = await this.listRuleTemplates(service, args.logger, { id, name });
if (!rules.length) {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
}
const result = rules[0];
result.arn = Resource.formatArn(region, awsAccountId, result.id);
args.logger.log({ action, message: 'done', result });
return Promise.resolve(result);
} catch (err) {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
}
}
Example #7
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
private async listRuleTemplates(service: CodeCommit, logger: Logger, filter?: Pick<ResourceModel, 'id' | 'name'>): Promise<ResourceModel[]> {
let rules: ResourceModel[] = [];
if (service) {
logger.log({ message: 'before invoke listApprovalRuleTemplates' });
const response = await service.listApprovalRuleTemplates().promise();
logger.log({ message: 'after invoke listApprovalRuleTemplates', response });
rules = await Promise.all(
response.approvalRuleTemplateNames.map((approvalRuleTemplateName: string) => {
return this.getRuleTemplate(service, logger, approvalRuleTemplateName);
})
);
if (filter) {
return rules.filter((rule: ResourceModel) => {
return (filter.id && filter.id === rule.id) || (filter.name && filter.name === rule.name);
});
}
}
return Promise.resolve(rules);
}
Example #8
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
private async getRuleTemplate(service: CodeCommit, logger: Logger, approvalRuleTemplateName: string): Promise<ResourceModel> {
const request: CodeCommit.GetApprovalRuleTemplateInput = {
approvalRuleTemplateName,
};
logger.log({ message: 'before invoke getApprovalRuleTemplate', request });
const response = await service.getApprovalRuleTemplate(request).promise();
logger.log({ message: 'after invoke getApprovalRuleTemplate', response });
const { approvalRuleTemplateId, approvalRuleTemplateContent } = response.approvalRuleTemplate;
const model = new ResourceModel();
model.id = approvalRuleTemplateId;
model.name = approvalRuleTemplateName;
model.description = response.approvalRuleTemplate.approvalRuleTemplateDescription;
model.creationDate = Resource.convertToEpoch(response.approvalRuleTemplate.creationDate);
model.lastModifiedDate = Resource.convertToEpoch(response.approvalRuleTemplate.lastModifiedDate);
model.lastModifiedUser = response.approvalRuleTemplate.lastModifiedUser;
model.ruleContentSha256 = response.approvalRuleTemplate.ruleContentSha256;
model.content = approvalRuleTemplateContent && TemplateContent.deserialize(JSON.parse(approvalRuleTemplateContent));
return Promise.resolve(model);
}
Example #9
Source File: handlers.ts From aws-resource-providers with MIT License | 5 votes |
@handlerEvent(Action.Create)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async create(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
if (model.arn) {
throw new exceptions.InvalidRequest('Read only property [Arn] cannot be provided by the user.');
} else if (model.id) {
throw new exceptions.InvalidRequest('Read only property [Id] cannot be provided by the user.');
}
const request: CodeCommit.CreateApprovalRuleTemplateInput = {
approvalRuleTemplateName: model.name,
approvalRuleTemplateDescription: model.description,
approvalRuleTemplateContent: model.content && JSON.stringify(model.content.serialize()),
};
try {
args.logger.log({ action, message: 'before createApprovalRuleTemplate', request });
const response = await service.createApprovalRuleTemplate(request).promise();
args.logger.log({ action, message: 'after invoke createApprovalRuleTemplate', response });
const { approvalRuleTemplateId, approvalRuleTemplateName } = response.approvalRuleTemplate;
const result = new ResourceModel();
result.arn = Resource.formatArn(region, awsAccountId, approvalRuleTemplateId);
result.id = approvalRuleTemplateId;
result.name = approvalRuleTemplateName;
result.description = response.approvalRuleTemplate.approvalRuleTemplateDescription;
result.content = model.content;
result.creationDate = Resource.convertToEpoch(response.approvalRuleTemplate.creationDate);
result.lastModifiedDate = Resource.convertToEpoch(response.approvalRuleTemplate.lastModifiedDate);
result.lastModifiedUser = response.approvalRuleTemplate.lastModifiedUser;
result.ruleContentSha256 = response.approvalRuleTemplate.ruleContentSha256;
args.logger.log({ action, message: 'done', result });
return Promise.resolve(result);
} catch (err) {
console.log(err);
if (err?.code === 'ApprovalRuleTemplateNameAlreadyExistsException') {
throw new exceptions.AlreadyExists(this.typeName, logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
}
}
Example #10
Source File: handlers.ts From aws-resource-providers with MIT License | 5 votes |
@handlerEvent(Action.Update)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async update(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, previousResourceState, region } = args.request;
const { arn, id } = previousResourceState;
if (!model.arn && !model.id) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
} else if (model.arn !== arn) {
args.logger.log(this.typeName, `[NEW ${model.arn}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${arn}].`);
throw new exceptions.NotUpdatable('Read only property [Arn] cannot be updated.');
} else if (model.id !== id) {
args.logger.log(this.typeName, `[NEW ${model.id}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${id}].`);
throw new exceptions.NotUpdatable('Read only property [Id] cannot be updated.');
}
try {
const serializedContent = model.content && model.content.serialize();
if (serializedContent !== previousResourceState.content.serialize()) {
const request: CodeCommit.UpdateApprovalRuleTemplateContentInput = {
approvalRuleTemplateName: previousResourceState.name,
// existingRuleContentSha256: previousResourceState.ruleContentSha256, # Removing because this will only succeed if content has been modified by CFN
newRuleContent: JSON.stringify(serializedContent),
};
args.logger.log({ action, message: 'before updateApprovalRuleTemplateContent', request });
const response = await service.updateApprovalRuleTemplateContent(request).promise();
args.logger.log({ action, message: 'after invoke updateApprovalRuleTemplateContent', response });
}
if (model.description !== previousResourceState.description) {
const request: CodeCommit.UpdateApprovalRuleTemplateDescriptionInput = {
approvalRuleTemplateName: previousResourceState.name,
approvalRuleTemplateDescription: model.description,
};
args.logger.log({ action, message: 'before updateApprovalRuleTemplateDescription', request });
const response = await service.updateApprovalRuleTemplateDescription(request).promise();
args.logger.log({ action, message: 'after invoke updateApprovalRuleTemplateDescription', response });
}
if (model.name !== previousResourceState.name) {
const request: CodeCommit.UpdateApprovalRuleTemplateNameInput = {
oldApprovalRuleTemplateName: previousResourceState.name,
newApprovalRuleTemplateName: model.name,
};
args.logger.log({ action, message: 'before invoke updateApprovalRuleTemplateName', request });
const response = await service.updateApprovalRuleTemplateName(request).promise();
args.logger.log({ action, message: 'after invoke updateApprovalRuleTemplateName', response });
}
model = await this.getRuleTemplate(service, args.logger, model.name);
model.arn = Resource.formatArn(region, awsAccountId, model.id);
args.logger.log({ action, message: 'done', model });
return Promise.resolve(model);
} catch (err) {
if (err?.code === 'ApprovalRuleTemplateDoesNotExistException') {
throw new exceptions.NotFound(this.typeName, id || logicalResourceIdentifier);
} else {
// Raise the original exception
throw err;
}
}
}
Example #11
Source File: codecommit.ts From aws-codecommit-devops-model with MIT No Attribution | 5 votes |
codecommit = new CodeCommit()
Example #12
Source File: handlers.ts From aws-resource-providers with MIT License | 5 votes |
@handlerEvent(Action.Create)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async create(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { awsAccountId, logicalResourceIdentifier, region } = args.request;
let approvalRuleTemplateId: string;
if (model.arn) {
throw new exceptions.InvalidRequest('Read only property [Arn] cannot be provided by the user.');
}
if (model.approvalRuleTemplateArn) {
approvalRuleTemplateId = Resource.extractResourceId(model.approvalRuleTemplateArn);
const approvalRuleTemplate = await this.getRuleTemplate(service, args.logger, { id: approvalRuleTemplateId });
model.approvalRuleTemplateName = approvalRuleTemplate.approvalRuleTemplateName;
} else {
const approvalRuleTemplate = await this.getRuleTemplate(service, args.logger, { name: model.approvalRuleTemplateName });
approvalRuleTemplateId = approvalRuleTemplate.approvalRuleTemplateId;
}
await this.listRepositoryAssociations(service, args.logger, model)
.catch((err: exceptions.BaseHandlerException) => {
if (err instanceof exceptions.NotFound) {
throw err;
}
args.logger.log(err);
return Promise.resolve(null);
})
.then((result: ResourceModel) => {
if (result?.repositoryNames?.length) {
throw new exceptions.AlreadyExists(this.typeName, model.approvalRuleTemplateName || logicalResourceIdentifier);
}
return Promise.resolve(null);
});
const request: CodeCommit.BatchAssociateApprovalRuleTemplateWithRepositoriesInput = {
approvalRuleTemplateName: model.approvalRuleTemplateName,
repositoryNames: model.repositoryNames,
};
args.logger.log({ action, message: 'after batchAssociateApprovalRuleTemplateWithRepositories', request });
const response = await service.batchAssociateApprovalRuleTemplateWithRepositories(request).promise();
args.logger.log({ action, message: 'after invoke batchAssociateApprovalRuleTemplateWithRepositories', response });
await this.checkBatchResponse(response, args.logger);
model.repositoryNames = response.associatedRepositoryNames;
model.arn = Resource.formatArn(region, awsAccountId, approvalRuleTemplateId);
args.logger.log({ action, message: 'done', model });
return Promise.resolve(model);
}
Example #13
Source File: handlers.ts From aws-resource-providers with MIT License | 5 votes |
@handlerEvent(Action.Update)
@commonAws({ serviceName: 'CodeCommit', debug: true })
public async update(action: Action, args: HandlerArgs<ResourceModel>, service: CodeCommit, model: ResourceModel): Promise<ResourceModel> {
const { logicalResourceIdentifier, previousResourceState } = args.request;
const { approvalRuleTemplateArn, approvalRuleTemplateName, arn } = previousResourceState;
if (!model.arn) {
throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
} else if (model.arn !== arn) {
args.logger.log(this.typeName, `[NEW ${model.arn}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${arn}].`);
throw new exceptions.NotUpdatable('Read only property [Arn] cannot be updated.');
} else if (model.approvalRuleTemplateArn && model.approvalRuleTemplateArn !== approvalRuleTemplateArn) {
args.logger.log(this.typeName, `[NEW ${model.approvalRuleTemplateArn}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${approvalRuleTemplateArn}].`);
throw new exceptions.NotUpdatable('Create only property [ApprovalRuleTemplateArn] cannot be updated.');
} else if (model.approvalRuleTemplateName && model.approvalRuleTemplateName !== approvalRuleTemplateName) {
args.logger.log(
this.typeName,
`[NEW ${model.approvalRuleTemplateName}] [${logicalResourceIdentifier}]`,
`does not match identifier from saved resource [OLD ${approvalRuleTemplateName}].`
);
throw new exceptions.NotUpdatable('Create only property [ApprovalRuleTemplateName] cannot be updated.');
}
const approvalRuleTemplateId = Resource.extractResourceId(arn);
const approvalRuleTemplate = await this.getRuleTemplate(service, args.logger, { id: approvalRuleTemplateId });
model.approvalRuleTemplateName = approvalRuleTemplate.approvalRuleTemplateName;
const result = await this.listRepositoryAssociations(service, args.logger, model);
if (!result.repositoryNames?.length) {
throw new exceptions.NotFound(this.typeName, model.approvalRuleTemplateName);
}
// First disassociate all repositories from previous state for the rule name
const requestRemoval: CodeCommit.BatchDisassociateApprovalRuleTemplateFromRepositoriesInput = {
approvalRuleTemplateName: model.approvalRuleTemplateName,
repositoryNames: previousResourceState.repositoryNames,
};
args.logger.log({ action, message: 'before batchDisassociateApprovalRuleTemplateFromRepositories', requestRemoval });
const responseRemoval = await service.batchDisassociateApprovalRuleTemplateFromRepositories(requestRemoval).promise();
args.logger.log({ action, message: 'after invoke batchDisassociateApprovalRuleTemplateFromRepositories', responseRemoval });
await this.checkBatchResponse(responseRemoval, args.logger);
// Then associate repositories from desired state to the rule name
const request: CodeCommit.BatchAssociateApprovalRuleTemplateWithRepositoriesInput = {
approvalRuleTemplateName: model.approvalRuleTemplateName,
repositoryNames: model.repositoryNames,
};
args.logger.log({ action, message: 'before batchAssociateApprovalRuleTemplateWithRepositories', request });
const response = await service.batchAssociateApprovalRuleTemplateWithRepositories(request).promise();
args.logger.log({ action, message: 'after invoke batchAssociateApprovalRuleTemplateWithRepositories', response });
await this.checkBatchResponse(response, args.logger);
model.repositoryNames = response.associatedRepositoryNames;
args.logger.log({ action, message: 'done', model });
return Promise.resolve(model);
}
Example #14
Source File: handler.ts From aws-codecommit-devops-model with MIT No Attribution | 5 votes |
codecommit = new CodeCommit()
Example #15
Source File: codecommit.ts From aws-codecommit-devops-model with MIT No Attribution | 5 votes |
approvalRuleTemplate: CloudFormationCustomResourceHandler = async (event, _context) => {
console.info(`Receiving ApprovalRuleEvent of CodeCommit ${JSON.stringify(event, null, 2)}`);
var responseData: any;
var result = SUCCESS;
var reason: any = '';
var resourceId: string | undefined = undefined;
try {
switch (event.RequestType) {
case 'Create':
const createTempalteResponse = await codecommit.createApprovalRuleTemplate({
approvalRuleTemplateName: event.ResourceProperties.ApprovalRuleTemplateName,
approvalRuleTemplateDescription: event.ResourceProperties.ApprovalRuleTemplateDescription || '',
approvalRuleTemplateContent: buildTemplateContent(event.ResourceProperties),
}).promise();
console.info(`Created approval rule template ${JSON.stringify(createTempalteResponse.$response.data, null, 2)}.`);
responseData = (createTempalteResponse.$response.data as CodeCommit.Types.CreateApprovalRuleTemplateOutput).approvalRuleTemplate;
resourceId = responseData.approvalRuleTemplateId;
break;
case 'Update':
const updateEvent = event as CloudFormationCustomResourceUpdateEvent;
resourceId = updateEvent.PhysicalResourceId;
const changes = [];
if (!equal(updateEvent.ResourceProperties.Template, updateEvent.OldResourceProperties.Template)) {
changes.push(codecommit.updateApprovalRuleTemplateContent({
approvalRuleTemplateName: updateEvent.OldResourceProperties.ApprovalRuleTemplateName,
newRuleContent: buildTemplateContent(updateEvent.ResourceProperties),
}).promise())
}
if (updateEvent.ResourceProperties.ApprovalRuleTemplateDescription !== updateEvent.OldResourceProperties.ApprovalRuleTemplateDescription) {
changes.push(codecommit.updateApprovalRuleTemplateDescription({
approvalRuleTemplateName: updateEvent.OldResourceProperties.ApprovalRuleTemplateName,
approvalRuleTemplateDescription: updateEvent.ResourceProperties.ApprovalRuleTemplateDescription || '',
}).promise());
}
if (changes.length > 0) {
const updateDescAndTemplateRt = await Promise.all(changes);
console.info(`Updated approval rule '${updateEvent.OldResourceProperties.ApprovalRuleTemplateName}' descirption and template content ${updateDescAndTemplateRt}.`);
responseData = (updateDescAndTemplateRt[0].$response.data as CodeCommit.Types.UpdateApprovalRuleTemplateContentOutput |
CodeCommit.Types.UpdateApprovalRuleTemplateDescriptionOutput).approvalRuleTemplate;
}
if (updateEvent.ResourceProperties.ApprovalRuleTemplateName !== updateEvent.OldResourceProperties.ApprovalRuleTemplateName) {
const updatedApprovalTemplate = await codecommit.updateApprovalRuleTemplateName({
newApprovalRuleTemplateName: updateEvent.ResourceProperties.ApprovalRuleTemplateName,
oldApprovalRuleTemplateName: updateEvent.OldResourceProperties.ApprovalRuleTemplateName,
}).promise();
console.log(`Updated approval rule name from '${updateEvent.OldResourceProperties.ApprovalRuleTemplateName} to '${updateEvent.ResourceProperties.ApprovalRuleTemplateName}'.`)
responseData = (updatedApprovalTemplate as CodeCommit.Types.UpdateApprovalRuleTemplateNameOutput).approvalRuleTemplate;
}
break;
case 'Delete':
const deleteEvent = event as CloudFormationCustomResourceDeleteEvent;
resourceId = deleteEvent.PhysicalResourceId;
const deleteTempalteResponse = await codecommit.deleteApprovalRuleTemplate({
approvalRuleTemplateName: event.ResourceProperties.ApprovalRuleTemplateName,
}).promise();
console.info(`Deleted approval rule template ${JSON.stringify(deleteTempalteResponse.$response.data, null, 2)}.`);
responseData = deleteTempalteResponse.$response.data;
break;
}
} catch (err) {
if (err instanceof Error) {
console.error(`Failed to create approval rule template due to ${err}.`);
responseData = err.message;
result = FAILED;
reason = err.message;
}
}
return await sendResponse({ Status: result, Reason: reason, PhysicalResourceId: (resourceId ? resourceId : _context.logStreamName), Data: responseData }, event);
}
Example #16
Source File: handlers.test.ts From aws-resource-providers with MIT License | 4 votes |
describe('when calling handler', () => {
let testEntrypointPayload: any;
let spySession: jest.SpyInstance;
let spySessionClient: jest.SpyInstance;
let codecommit: AwsServiceMockBuilder<CodeCommit>;
let fixtureMap: Map<Action, Record<string, any>>;
beforeAll(() => {
fixtureMap = new Map<Action, Record<string, any>>();
fixtureMap.set(Action.Create, createFixture);
fixtureMap.set(Action.Read, readFixture);
fixtureMap.set(Action.Update, updateFixture);
fixtureMap.set(Action.Delete, deleteFixture);
});
beforeEach(async () => {
codecommit = on(CodeCommit, { snapshot: false });
codecommit.mock('batchAssociateApprovalRuleTemplateWithRepositories').resolve({
associatedRepositoryNames: [],
errors: [],
});
codecommit.mock('batchDisassociateApprovalRuleTemplateFromRepositories').resolve({
disassociatedRepositoryNames: [],
errors: [],
});
codecommit.mock('listRepositoriesForApprovalRuleTemplate').resolve({
repositoryNames: ['repo1', 'repo2'],
});
codecommit.mock('getApprovalRuleTemplate').resolve({
approvalRuleTemplate: {
approvalRuleTemplateId: 'ecc5e2e3-9bf4-4589-8759-8e788983c1fb',
approvalRuleTemplateName: 'test',
approvalRuleTemplateContent: '',
},
});
codecommit.mock('listApprovalRuleTemplates').resolve({
approvalRuleTemplateNames: ['test', 'test2'],
});
spySession = jest.spyOn(SessionProxy, 'getSession');
spySessionClient = jest.spyOn<any, any>(SessionProxy.prototype, 'client');
spySessionClient.mockReturnValue(codecommit.instance);
testEntrypointPayload = {
credentials: { accessKeyId: '', secretAccessKey: '', sessionToken: '' },
region: 'us-east-1',
action: 'CREATE',
};
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
test('create operation successful - code commit repository association', async () => {
const request = fixtureMap.get(Action.Create);
codecommit.mock('batchAssociateApprovalRuleTemplateWithRepositories').resolve({
associatedRepositoryNames: ['repo1', 'repo2'],
errors: [],
});
codecommit.mock('listRepositoriesForApprovalRuleTemplate').resolve({ repositoryNames: [] });
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject({
...request.desiredResourceState,
Arn: IDENTIFIER,
});
});
test('create operation fail not found - code commit repository association', async () => {
expect.assertions(4);
const mockGet = codecommit.mock('listRepositoriesForApprovalRuleTemplate').reject({
...new Error(),
code: 'ApprovalRuleTemplateDoesNotExistException',
});
const spyRetrieve = jest.spyOn<any, any>(resource, 'listRepositoryAssociations');
const request = fixtureMap.get(Action.Create);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
expect(mockGet.mock).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveReturned();
});
test('update operation successful - code commit repository association', async () => {
const request = fixtureMap.get(Action.Update);
codecommit.mock('batchAssociateApprovalRuleTemplateWithRepositories').resolve({
associatedRepositoryNames: ['repo1', 'repo3'],
errors: [],
});
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Update, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('delete operation successful - code commit repository association', async () => {
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel).toBeNull();
});
test('delete operation fail not found - code commit repository association', async () => {
expect.assertions(4);
const mockGet = codecommit.mock('listRepositoriesForApprovalRuleTemplate').reject({
...new Error(),
code: 'ApprovalRuleTemplateDoesNotExistException',
});
const spyRetrieve = jest.spyOn<any, any>(resource, 'listRepositoryAssociations');
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
expect(mockGet.mock).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveReturned();
});
test('delete operation fail generic', async () => {
expect.assertions(2);
const mockDelete = codecommit.mock('batchDisassociateApprovalRuleTemplateFromRepositories').resolve({
errors: [
{
errorMessage: 'The specified repository does not exist.',
errorCode: 'RepositoryDoesNotExistException',
},
],
});
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.InternalFailure.name });
expect(mockDelete.mock).toHaveBeenCalledTimes(1);
});
test('read operation successful - code commit repository association', async () => {
const request = fixtureMap.get(Action.Read);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject({
...request.desiredResourceState,
RepositoryNames: ['repo1', 'repo2'],
});
});
test('read operation fail not found - code commit repository association', async () => {
expect.assertions(4);
const mockGet = codecommit.mock('listRepositoriesForApprovalRuleTemplate').resolve({ repositoryNames: [] });
const spyRetrieve = jest.spyOn<any, any>(resource, 'listRepositoryAssociations');
const request = fixtureMap.get(Action.Read);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
expect(mockGet.mock).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveReturned();
});
test('all operations fail without session - code commit repository association', async () => {
expect.assertions(fixtureMap.size);
spySession.mockReturnValue(null);
for (const [action, request] of fixtureMap) {
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action, request }, null);
expect(progress.errorCode).toBe(exceptions.InvalidCredentials.name);
}
});
});
Example #17
Source File: handlers.test.ts From aws-resource-providers with MIT License | 4 votes |
describe('when calling handler', () => {
let testEntrypointPayload: any;
let spySession: jest.SpyInstance;
let spySessionClient: jest.SpyInstance;
let codecommit: AwsServiceMockBuilder<CodeCommit>;
let fixtureMap: Map<Action, Record<string, any>>;
beforeAll(() => {
fixtureMap = new Map<Action, Record<string, any>>();
fixtureMap.set(Action.Create, createFixture);
fixtureMap.set(Action.Read, readFixture);
fixtureMap.set(Action.Update, updateFixture);
fixtureMap.set(Action.Delete, deleteFixture);
});
beforeEach(async () => {
codecommit = on(CodeCommit, { snapshot: false });
codecommit.mock('getApprovalRuleTemplate').resolve({
approvalRuleTemplate: {
approvalRuleTemplateId: 'ecc5e2e3-9bf4-4589-8759-8e788983c1fb',
approvalRuleTemplateName: 'test',
approvalRuleTemplateContent: '',
},
});
codecommit.mock('listApprovalRuleTemplates').resolve({
approvalRuleTemplateNames: ['test', 'test2'],
});
codecommit.mock('createApprovalRuleTemplate').resolve({
approvalRuleTemplate: {
approvalRuleTemplateName: 'test',
approvalRuleTemplateId: IDENTIFIER,
approvalRuleTemplateDescription: 'test',
approvalRuleTemplateContent: '',
},
});
codecommit.mock('updateApprovalRuleTemplateContent').resolve({ approvalRuleTemplate: {} });
codecommit.mock('updateApprovalRuleTemplateDescription').resolve({ approvalRuleTemplate: {} });
codecommit.mock('updateApprovalRuleTemplateName').resolve({ approvalRuleTemplate: {} });
codecommit.mock('deleteApprovalRuleTemplate').resolve({});
spySession = jest.spyOn(SessionProxy, 'getSession');
spySessionClient = jest.spyOn<any, any>(SessionProxy.prototype, 'client');
spySessionClient.mockReturnValue(codecommit.instance);
testEntrypointPayload = {
credentials: { accessKeyId: '', secretAccessKey: '', sessionToken: '' },
region: 'us-east-1',
action: 'CREATE',
};
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
test('create operation successful - code commit approval rule template', async () => {
const request = fixtureMap.get(Action.Create);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject({
...request.desiredResourceState,
Id: IDENTIFIER,
});
});
test('create operation fail already exists - code commit approval rule template', async () => {
expect.assertions(2);
const mockCreate = codecommit.mock('createApprovalRuleTemplate').reject({
...new Error(),
code: 'ApprovalRuleTemplateNameAlreadyExistsException',
});
const request = fixtureMap.get(Action.Create);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.AlreadyExists.name });
expect(mockCreate.mock).toHaveBeenCalledTimes(1);
});
test('update operation successful - code commit approval rule template', async () => {
const request = fixtureMap.get(Action.Update);
codecommit.mock('getApprovalRuleTemplate').resolve({
approvalRuleTemplate: {
approvalRuleTemplateId: '8f9be413-f9cc-49a1-b901-0a59a6f126c2',
approvalRuleTemplateName: 'test2',
approvalRuleTemplateDescription: 'test2',
approvalRuleTemplateContent:
'{"Version": "2018-11-08","DestinationReferences": ["refs/heads/master"],"Statements": [{"Type": "Approvers","NumberOfApprovalsNeeded": 3,"ApprovalPoolMembers": ["*"]}]}',
},
});
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Update, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('delete operation successful - code commit approval rule template', async () => {
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel).toBeNull();
});
test('delete operation fail not found - code commit approval rule template', async () => {
expect.assertions(4);
const mockGet = codecommit.mock('listApprovalRuleTemplates').reject({
...new Error(),
code: 'ApprovalRuleTemplateDoesNotExistException',
});
const spyRetrieve = jest.spyOn<any, any>(resource, 'listRuleTemplates');
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
expect(mockGet.mock).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveReturned();
});
test('read operation successful - code commit approval rule template', async () => {
const request = fixtureMap.get(Action.Read);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('read operation fail not found - code commit approval rule template', async () => {
expect.assertions(4);
const mockGet = codecommit.mock('listApprovalRuleTemplates').reject({
...new Error(),
code: 'ApprovalRuleTemplateDoesNotExistException',
});
const spyRetrieve = jest.spyOn<any, any>(resource, 'listRuleTemplates');
const request = fixtureMap.get(Action.Read);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
expect(mockGet.mock).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveBeenCalledTimes(1);
expect(spyRetrieve).toHaveReturned();
});
test('all operations fail without session - code commit approval rule template', async () => {
expect.assertions(fixtureMap.size);
spySession.mockReturnValue(null);
for (const [action, request] of fixtureMap) {
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action, request }, null);
expect(progress.errorCode).toBe(exceptions.InvalidCredentials.name);
}
});
});