import { createAskSdkError , PersistenceAdapter } from 'ask-sdk-core' ; import { RequestEnvelope } from 'ask-sdk-model' ; import { S3 } from 'aws-sdk' ; import * as path from 'path' ; import { ObjectKeyGenerator , ObjectKeyGenerators } from './ObjectKeyGenerators' ; /**
 * Implementation of  PersistenceAdapter using AWS S3
  export class S3PersistenceAdapter implements PersistenceAdapter { protected bucketName : string ; protected s3Client : S3 ; protected objectKeyGenerator : ObjectKeyGenerator ; protected pathPrefix : string ; constructor ( config ) { this . bucketName = config . bucketName ; this . s3Client = config . s3Client ? config . s3Client : new S3 ( { apiVersion : 'latest' } ) ; this . objectKeyGenerator = config . objectKeyGenerator ? config . objectKeyGenerator : ObjectKeyGenerators . userId ; this . pathPrefix = config . pathPrefix ? config . pathPrefix : '' ; } param { RequestEnvelope } requestEnvelope returns { Promise < Object . < string , any > > } public async getAttributes ( requestEnvelope ) { const objectId = path . join ( this . pathPrefix , this . objectKeyGenerator ( requestEnvelope ) ) ; const getParams = { Bucket : this . bucketName , Key : objectId , } ; let data ; try { data = await this . s3Client . getObject ( getParams ) . promise ( ) ; } catch ( err ) { if ( err . code === 'NoSuchKey' ) { return { } ; } throw createAskSdkError ( this . constructor . name , `Could not read item (${ objectId }) from bucket (${ getParams . Bucket }): ${ err . message }` ) ; } const bodyString = data . Body ? data . Body . toString ( ) : '' ; let bodyObj ; try { bodyObj = bodyString ? JSON . parse ( bodyString ) : { } ; } catch ( err ) { throw new SyntaxError ( `Failed trying to parse the data body: ${ data . Body . toString ( ) }` ) ; } return bodyObj ; } param { RequestEnvelope } requestEnvelope param { Object . < string , any > } attributes return { Promise < void > } public async saveAttributes ( requestEnvelope , attributes ) { const objectId = path . join ( this . pathPrefix , this . objectKeyGenerator ( requestEnvelope ) ) ; const putParams = { Bucket : this . bucketName , Key : objectId , Body : JSON . stringify ( attributes ) , } ; try { await this . s3Client . putObject ( putParams ) . promise ( ) ; } catch ( err ) { throw createAskSdkError ( this . constructor . name , `Could not save item (${ objectId }) to bucket (${ putParams . Bucket }): ${ err . message }` ) ; } } public async deleteAttributes ( requestEnvelope ) { const objectId = path . join ( this . pathPrefix , this . objectKeyGenerator ( requestEnvelope ) ) ; const deleteParams = { Bucket : this . bucketName , Key : objectId , } ; try { await this . s3Client . deleteObject ( deleteParams ) . promise ( ) ; } catch ( err ) { throw createAskSdkError ( this . constructor . name , `Could not delete item (${ objectId }) from bucket (${ deleteParams . Bucket }): ${ err . message }` ) ; } } }