in resource-types/typescript-example-website-monitor/src/handlers.ts [172:232]
public async update(
session: Optional<SessionProxy>,
request: ResourceHandlerRequest<ResourceModel>,
callbackContext: CallbackContext,
logger: LoggerProxy
): Promise<ProgressEvent> {
logger.log('request', request);
const model = new ResourceModel(request.desiredResourceState);
const { id, name } = request.previousResourceState;
if (!model.id) {
throw new exceptions.NotFound(this.typeName, request.logicalResourceIdentifier);
} else if (model.id !== id) {
logger.log(this.typeName, `[NEW ${model.id}] [${request.logicalResourceIdentifier}] does not match identifier from saved resource [OLD ${id}].`);
throw new exceptions.NotUpdatable('Read only property [Id] cannot be updated.');
} else if (model.name !== name) {
// The Name is a create only property, which means that it cannot be updated.
logger.log(this.typeName, `[NEW ${model.name}] [${request.logicalResourceIdentifier}] does not match identifier from saved resource [OLD ${name}].`);
throw new exceptions.NotUpdatable('Create only property [Name] cannot be updated.');
}
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;
// Update the synthetics monitor by calling the endpoint with its ID.
// https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#update-monitor
const apiKey = model.apiKey;
const apiEndpoint = ApiEndpoints[model.endpointRegion as EndpointRegions];
const response: Response = await fetch(`${apiEndpoint}/v3/monitors/${id}`, {
method: 'PUT',
headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': apiKey },
body: JSON.stringify({
name,
uri: model.uri,
type: model.kind,
frequency: model.frequency,
status: model.status,
locations: model.locations,
slaThreshold: model.slaThreshold
} as Monitor)
});
await this.checkResponse(response, logger, id);
// model.apiKey = null;
const progress = ProgressEvent.success<ProgressEvent<ResourceModel>>(model);
logger.log('progress', progress);
return progress;
} catch(err) {
logger.log(err);
if (err instanceof exceptions.BaseHandlerException) {
throw err;
}
return ProgressEvent.failed<ProgressEvent<ResourceModel>>(HandlerErrorCode.InternalFailure, err.message);
}
}