function publish_indices()

in aws/lambdas/create-s3-index-html/index.js [38:98]


function publish_indices(event, all_objs, callback) {
  const month_ago = Date.now() - 30 * 24 * 60 * 60 * 1000;
  const filtered_objs = all_objs.filter(obj =>
    !obj.Key.endsWith('/index.html') &&
    obj.LastModified.getTime() > month_ago
  );

  let dirs = new Set(['']);
  filtered_objs.forEach(obj => {
    let parts = obj.Key.split('/');
    parts.pop();
    while (parts.length > 0) {
      dirs.add(parts.join('/'));
      parts.pop();
    }
  });

  dirs = Array.from(dirs.values());

  const s3 = new AWS.S3();
  const s3_upload_promises = dirs.map(dir => s3.putObject({
      ContentType: 'text/html',
      Body: get_index_html_string(dir, all_objs),
      Bucket: event.bucket,
      Key: (dir+'/index.html').replace(/^\/+/, '')
  }).promise());
  Promise.all(s3_upload_promises).catch(err => callback(err)).then(data => {
    if (!event.cloudfront) {
      callback(null, data);
    }
    // Invalidate the CDN
    const cloudfront = new AWS.CloudFront();
    cloudfront.createInvalidation(
      {
        DistributionId: event.cloudfront,
        InvalidationBatch: {
          CallerReference: 's3-index-update-'+(new Date()).toISOString(),
          Paths: {
            Quantity: dirs.length,
            Items: dirs.map(
              dir => dir === '' ? '/' : ('/'+dir+'/')
            )
          }
        }
      },
      (err, data) => {
        try {
          const paths = data.Invalidation.InvalidationBatch.Paths.Items;
          if (paths.length > 17) {
            data.Invalidation.InvalidationBatch.Paths.Items = [
              ...paths.slice(0, 8),
              '-- truncated --',
              ...paths.slice(-8),
            ];
          }
        } catch (e) {}
        callback(err, data);
      }
    );
  }).catch(err => callback(err));
}