alexa / alexa-skills-kit-sdk-for-nodejs

The Alexa Skills Kit SDK for Node.js helps you get a skill up and running quickly, letting you focus on skill logic instead of boilerplate code.
Apache License 2.0
3.12k stars 736 forks source link

feat: add new util function (getRequest) #582

Closed hideokamoto closed 4 years ago

hideokamoto commented 5 years ago

The getRequest() function helps us to make a skill by using TypeScript. We can get a specific type of the request object.

Description

Add a new util function getRequest. To get request object with own expected type.

Motivation and Context

Related: Missing typescript definitions? #398

Currently

We can get the request object by the code.

const { request} = handlerInput.requestEnvelope

But the object has several type, so we can not get any property without using any.

// ERROR
const state = handlerInput.requestEnvelope.request.dialogState

-> Property 'dialogState' does not exist on type 'PlaybackFinishedRequest'.

// PASS
const state = (handlerInput.requestEnvelope.request as IntentRequest).dialogState

But these coding style is not comfortable and hard to understand for a new developer.

Solution

The getRequest function is my solution. It can update the request object type by using TypeScript Generics.

// For Intent request
const request = getRequest<IntentRequest>(handlerInput.requestEnvelope)
const state = request.dialogState

// For AudioPlayer intent request
const req = getRequest<interfaces.audioplayer.PlaybackFinishedRequest>(intentRequestEnvelope)
const sec = req.offsetInMilliseconds

Testing

$ lerna --scope ask-sdk-core run gulp

  113 passing (101ms)

=============================== Coverage summary ===============================
Statements   : 100% ( 357/357 )
Branches     : 98.99% ( 98/99 )
Functions    : 96.33% ( 105/109 )
Lines        : 100% ( 336/336 )
================================================================================

[00:17:25] Finished 'test' after 2.59 s
[00:17:26] Finished 'tsc' after 3.58 s
[00:17:26] Finished 'default' after 3.6 s
lerna success run Ran npm script 'gulp' in 1 package in 5.4s:
lerna success - ask-sdk-core

Screenshots (if appropriate)

Types of changes

Checklist

License

hideokamoto commented 4 years ago

@ShenChen-Amazon Thanks. I've fixed it today :)