Skip to content

Instantly share code, notes, and snippets.

View mgjam's full-sized avatar

Milan Gatyás mgjam

  • Czech Republic
View GitHub Profile
{
"Outputs": {
"bucketArn": {
"Value": {
"Fn::ImportValue": "exp:ExportsOutputFnGetAttExportedBucket5C9669B4ArnA5E36DA6"
}
}
},
"Resources": {
"CDKMetadata": {...}
{
"Resources": {
"ExportedBucket5C9669B4": {
"Type": "AWS::S3::Bucket",
"UpdateReplacePolicy": "Retain",
"DeletionPolicy": "Retain",
"Metadata": {
"aws:cdk:path": "exp/ExportedBucket/Resource"
}
},
export class ExportingStack extends Stack {
public readonly bucket: Bucket;
constructor(scope: Construct, id: string, props: StackProps) {
super(scope, id, props);
this.bucket = new Bucket(this, 'ExportedBucket');
}
}
// Having defined const api: RestApi
const robotsResource = api.root.addResource('robots.txt');
const headMethod = robotsResource.addMethod('HEAD', mockIntegration, methodOptions);
const getMethod = robotsResource.addMethod('GET', mockIntegration, methodOptions);
const methodOptions: MethodOptions = {
methodResponses: [{
statusCode: '200',
responseModels: {
'text/plain': Model.EMPTY_MODEL
}
}]
};
const mockIntegration = new MockIntegration({
requestTemplates: {
'application/json': '{"statusCode": 200}'
},
integrationResponses: [{
statusCode: '200',
responseTemplates: {
'text/plain':
`User-agent: *
Disallow: /
ISet<string> allowedOrigins; // ["https://my-origin-1.com", "https://my-origin-2.com"] received e.g. from SSM
var originHeader = request.headers.FirstOrDefault(x => "Origin".Equals(x.Key, StringComparison.InvariantCultureIgnoreCase));
// Only single allowed origin is possible in the response. Pick it based on the origin of the request
var allowedOrigin = allowedOrigins.Contains(originHeader.Value?.ToLower()) ? originHeader.Value : string.Empty;
return new // response
{
headers = new Dictionary<string, string>
{
{ "Access-Control-Allow-Origin", allowedOrigin },
// Request
{
...
"headers": {
"header1": "value1",
"header2": "value2"
},
...
}
// const origins = ['https://my-origin-1.com', 'https://my-origin-2.com'];
const responses: IntegrationResponse[] = [{
statusCode: "200",
responseTemplates: {
'application/json': getAllowOrigin(origins) + '$input.body' // or other template you need
}
}/*, ...rest of your responses */];
const getAllowOrigin = (origins: string[]) =>
{
const condition = origins
.map(x => `$origin.matches(\"${x}\")`)
.reduce((l,r) => `${l} || ${r}`);
return `#set($origin = $input.params(\"Origin\"))\n#if($origin == \"\") #set($origin = $input.params(\"origin\")) #end\n#if(${condition})\n #set($context.responseOverride.header.Access-Control-Allow-Origin = $origin)\n#end\n`;
}