import { createAskSdkError , Skill } from 'ask-sdk-core' ; import { ResponseEnvelope } from 'ask-sdk-model' ; import { text } from 'body-parser' ; import { RequestHandler } from 'express' ; import { asyncVerifyRequestAndDispatch } from '../util' ; import { SkillRequestSignatureVerifier , TimestampVerifier , Verifier } from '../verifier' ; /**
 * Express adapter class
 */ export class ExpressAdapter { protected skill : Skill ; protected verifiers : Verifier [ ] ; param { Skill } skill param { boolean } verifySignature param { boolean } verifyTimeStamp param { Verifier [ ] } verifiers constructor ( skill , verifySignature = true , verifyTimeStamp = true , verifiers = [ ] ) { this . skill = skill ; this . verifiers = verifiers ; if ( ! this . skill ) { throw createAskSdkError ( this . constructor . name , 'The input skill cannot be empty' ) ; } skill . appendAdditionalUserAgent ( 'ask-express-adapter' ) ; if ( verifySignature ) { verifiers . push ( new SkillRequestSignatureVerifier ( ) ) ; } if ( verifyTimeStamp ) { verifiers . push ( new TimestampVerifier ( ) ) ; } } /**
     * Get pre-defined request handlers
     *
     * This function return an array of pre-defined request handlers
     * which are supposed to be registered on users' express application, including:
     * 1: text parser 2: async function to get response envelope after verification, then send result back
     * Example usage: app.post('/', new ExpressAdapter(skill).getASKRequestHandler());
     */ public getRequestHandlers ( ) { const requestHandlers = [ ] ; requestHandlers . push ( ( req , res , next ) => { if ( req . body ) { res . statusCode = 500 ; res . send ( 'Error in processing request. Do not register any parsers before using the adapter' ) ; return ; } next ( ) ; } ) ; requestHandlers . push ( text ( { type : '*/*' , } ) ) ; requestHandlers . push ( async ( req , res ) => { try { const responseEnvelope = await asyncVerifyRequestAndDispatch ( req . headers , req . body , this . skill , this . verifiers ) ; res . json ( responseEnvelope ) ; } catch ( err ) { res . statusCode = err . name === 'AskSdk.Request verification failed Error' ? 400 : 500 ; res . send ( `${ err . name }, ${ err . message }` ) ; } } ) ; return requestHandlers ; } }