in resource-types/typescript-example-website-monitor/src/handlers.ts [87:159]
public async create(
session: Optional<SessionProxy>,
request: ResourceHandlerRequest<ResourceModel>,
callbackContext: CallbackContext,
logger: LoggerProxy
): Promise<ProgressEvent> {
logger.log('request', request);
// It is important that we create a new instance of the model,
// because the desired state is immutable.
const model = new ResourceModel(request.desiredResourceState);
const progress = ProgressEvent.progress<ProgressEvent<ResourceModel>>(model);
// Id is a read only property, which means that
// it cannot be set during creation or update operations.
if (model.id) {
throw new exceptions.InvalidRequest('Read only property [Id] cannot be provided by the user.');
}
try {
// Set or fallback to default values
model.frequency = model.frequency || Integer(5);
model.endpointRegion = model.endpointRegion || 'US';
model.kind = Resource.DEFAULT_MONITOR_KIND;
model.status = Resource.DEFAULT_MONITOR_STATUS;
model.locations = Resource.DEFAULT_MONITOR_LOCATIONS;
model.slaThreshold = Resource.DEFAULT_MONITOR_SLA_THRESHOLD;
// Create a new synthetics monitor
// https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#create-monitor
const apiKey = model.apiKey;
const apiEndpoint = ApiEndpoints[model.endpointRegion as EndpointRegions];
const createResponse: Response = await fetch(`${apiEndpoint}/v3/monitors`, {
method: 'POST',
headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': apiKey },
body: JSON.stringify({
name: model.name,
uri: model.uri,
type: model.kind,
frequency: model.frequency,
status: model.status,
locations: model.locations,
slaThreshold: model.slaThreshold
} as Monitor)
});
await this.checkResponse(createResponse, logger, request.logicalResourceIdentifier);
// Use address from location header to read newly created monitor
// https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#get-specific-monitor
const locationUrl = createResponse.headers.get('location');
if (!locationUrl) {
throw new exceptions.NotFound(this.typeName, request.logicalResourceIdentifier);
}
const response: Response = await fetch(locationUrl, {
method: 'GET',
headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': apiKey }
});
const monitor: Monitor = await this.checkResponse(response, logger, request.logicalResourceIdentifier);
model.id = monitor.id;
// model.apiKey = null;
// Setting Status to success will signal to CloudFormation that the operation is complete
progress.status = OperationStatus.Success;
} catch(err) {
logger.log(err);
if (err instanceof exceptions.BaseHandlerException) {
throw err;
}
throw new exceptions.InternalFailure(err.message);
}
logger.log('progress', progress);
return progress;
}