async onPOST()

in source/api/lib/operations/assetOp.js [71:134]


  async onPOST() {
    let params = this.request.body || {};
    if (!(params.uuid || (params.bucket && params.key))) {
      throw new Error('uuid or bucket and key must be specified');
    }

    if (params.uuid && !CommonUtils.validateUuid(params.uuid)) {
      throw new Error('invalid uuid');
    }

    if (params.bucket && !CommonUtils.validateBucket(params.bucket)) {
      throw new Error('invalid bucket name');
    }

    /* #1: make sure there is no uuid collision */
    let fetched;
    if (params.uuid) {
      const db = new DB({
        Table: Environment.DynamoDB.Ingest.Table,
        PartitionKey: Environment.DynamoDB.Ingest.PartitionKey,
      });
      fetched = await db.fetch(params.uuid, undefined, 'key').catch(() => undefined);

      if (params.key && (fetched || {}).key && params.key !== fetched.key) {
        throw new Error(`${params.uuid} is already used for other asset`);
      }
    }

    /* #2: make sure s3 object exists */
    const uuid = params.uuid || CommonUtils.uuid4();
    const bucket = params.bucket || Environment.Ingest.Bucket;
    const key = params.key || (fetched || {}).key;

    let response = await CommonUtils.headObject(bucket, key);

    /* #3: start ingest state machine */
    const arn = [
      'arn:aws:states',
      process.env.AWS_REGION,
      this.request.accountId,
      'stateMachine',
      Environment.StateMachines.Ingest,
    ].join(':');

    const step = new AWS.StepFunctions({
      apiVersion: '2016-11-23',
    });

    params = Object.assign({}, {
      uuid,
      bucket,
      key,
    }, params);

    response = await step.startExecution({
      input: JSON.stringify(params),
      stateMachineArn: arn,
    }).promise();

    return super.onPOST(Object.assign({
      uuid: params.uuid,
      status: StateData.Statuses.Started,
    }, response));
  }