UNPKG

cdk-iot-greengrass-fleet-provisioning

Version:

CDK Construct for AWS IoT Greengrass Fleet Provisioning (with AWS IoT Certificates)

78 lines (77 loc) 3.3 kB
import { HttpBindingProtocol, HttpInterceptingShapeDeserializer, HttpInterceptingShapeSerializer, } from "@smithy/core/protocols"; import { NormalizedSchema, SCHEMA } from "@smithy/core/schema"; import { ProtocolLib } from "../ProtocolLib"; import { JsonCodec } from "./JsonCodec"; import { loadRestJsonErrorCode } from "./parseJsonBody"; export class AwsRestJsonProtocol extends HttpBindingProtocol { serializer; deserializer; codec; mixin = new ProtocolLib(); constructor({ defaultNamespace }) { super({ defaultNamespace, }); const settings = { timestampFormat: { useTrait: true, default: SCHEMA.TIMESTAMP_EPOCH_SECONDS, }, httpBindings: true, jsonName: true, }; this.codec = new JsonCodec(settings); this.serializer = new HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); this.deserializer = new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); } getShapeId() { return "aws.protocols#restJson1"; } getPayloadCodec() { return this.codec; } setSerdeContext(serdeContext) { this.codec.setSerdeContext(serdeContext); super.setSerdeContext(serdeContext); } async serializeRequest(operationSchema, input, context) { const request = await super.serializeRequest(operationSchema, input, context); const inputSchema = NormalizedSchema.of(operationSchema.input); if (!request.headers["content-type"]) { const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); if (contentType) { request.headers["content-type"] = contentType; } } if (request.headers["content-type"] && !request.body) { request.body = "{}"; } if (request.body) { try { request.headers["content-length"] = this.mixin.calculateContentLength(request.body, this.serdeContext); } catch (e) { } } return request; } async handleError(operationSchema, context, response, dataObject, metadata) { const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); const ns = NormalizedSchema.of(errorSchema); const message = dataObject.message ?? dataObject.Message ?? "Unknown"; const exception = new errorSchema.ctor(message); await this.deserializeHttpMessage(errorSchema, context, response, dataObject); const output = {}; for (const [name, member] of ns.structIterator()) { const target = member.getMergedTraits().jsonName ?? name; output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); } throw Object.assign(exception, errorMetadata, { $fault: ns.getMergedTraits().error, message, }, output); } getDefaultContentType() { return "application/json"; } }