|
| 1 | +import { BuilderContext } from '@angular-devkit/architect'; |
| 2 | +import * as AWS from 'aws-sdk'; |
| 3 | +import { CreateInvalidationRequest } from 'aws-sdk/clients/cloudfront'; |
| 4 | +import { Schema } from './schema'; |
| 5 | +import { |
| 6 | + getAccessKeyId, |
| 7 | + getSecretAccessKey, |
| 8 | + getRegion, |
| 9 | + getSubFolder, |
| 10 | + getCfDistributionId |
| 11 | +} from './config'; |
| 12 | + |
| 13 | +export class CloudFront { |
| 14 | + private _builderConfig: Schema; |
| 15 | + private _context: BuilderContext; |
| 16 | + |
| 17 | + private _cloudFront: AWS.CloudFront; |
| 18 | + |
| 19 | + private _cfDistributionId: string; |
| 20 | + private _subFolder: string; |
| 21 | + private _region: string; |
| 22 | + |
| 23 | + constructor(context: BuilderContext, builderConfig: Schema) { |
| 24 | + this._context = context; |
| 25 | + this._builderConfig = builderConfig; |
| 26 | + |
| 27 | + this._region = getRegion(this._builderConfig); |
| 28 | + this._cfDistributionId = getCfDistributionId(this._builderConfig); |
| 29 | + this._subFolder = getSubFolder(this._builderConfig); |
| 30 | + |
| 31 | + AWS.config.update({ region: this._region }); |
| 32 | + this._cloudFront = new AWS.CloudFront({ |
| 33 | + apiVersion: 'latest', |
| 34 | + secretAccessKey: getSecretAccessKey(), |
| 35 | + accessKeyId: getAccessKeyId() |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + public async invalidate(): Promise<boolean> { |
| 40 | + if (!this._cfDistributionId) { |
| 41 | + this._context.logger.info('⚠️ Skipping invalidation of CloudFront distribution'); |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + const cf_path = this._subFolder ? `/${this._subFolder}/*` : '/*'; |
| 46 | + const reference = `ngx-aws-deploy-${new Date().getTime()}`; |
| 47 | + |
| 48 | + const params : CreateInvalidationRequest = { |
| 49 | + DistributionId: this._cfDistributionId, |
| 50 | + InvalidationBatch: { |
| 51 | + CallerReference: reference, |
| 52 | + Paths: { |
| 53 | + Quantity: 1, |
| 54 | + Items: [ |
| 55 | + cf_path |
| 56 | + ] |
| 57 | + } |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + this._context.logger.info(`Triggering invalidation of '${cf_path}' from CloudFront distribution ${this._cfDistributionId}`); |
| 62 | + |
| 63 | + await this._cloudFront |
| 64 | + .createInvalidation(params) |
| 65 | + .promise() |
| 66 | + .then((data) => { |
| 67 | + this._context.logger.info(`Successfully triggered invalidation of '${cf_path}' from CloudFront distribution ${this._cfDistributionId}: current status is '${data.Invalidation.Status}'`); |
| 68 | + }) |
| 69 | + .catch((error) => { |
| 70 | + this._context.logger.error(`❌ The following error was found during CloudFront invalidation ${error}`); |
| 71 | + throw error; |
| 72 | + }); |
| 73 | + |
| 74 | + return true; |
| 75 | + } |
| 76 | +} |
0 commit comments