Skip to content

Commit

Permalink
feat: implement timeout expired response
Browse files Browse the repository at this point in the history
  • Loading branch information
fletcherist committed Jul 13, 2018
1 parent c9f778f commit d853700
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 9 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
"scripts": {
"lint": "eslint src",
"test": "jest",
"dev": "tsc -w",
"build": "tsc",
"dev": "tsc -w --declaration",
"build": "rm -rf dist && tsc --declaration",
"version": "npm run changelog && git add CHANGELOG.md",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0",
"release": "conventional-github-releaser -p angular",
Expand Down
34 changes: 28 additions & 6 deletions src/alice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
selectCommand,
selectSessionId,
isFunction,
delay,
} from './utils'

import {
Expand All @@ -19,13 +20,17 @@ import {
import aliceStateMiddleware from './middlewares/aliceStateMiddleware'
import { configInterface } from './types/alice'
import { CommandInterface } from './types/command'
import { CtxInterface } from './types/ctx'
import { WebhookResponse, WebhookRequest } from 'webhook'

const DEFAULT_SESSIONS_LIMIT: number = 1000
const DEFAULT_TIMEOUT_CALLBACK_MESSAGE = 'Извините, но я не успела найти ответ за отведенное время.'
const DEFAULT_TIMEOUT_CALLBACK = 600

export default class Alice {
private anyCallback: (ctx: Ctx) => void
private welcomeCallback: (ctx: Ctx) => void
private anyCallback: (ctx: CtxInterface) => void
private welcomeCallback: (ctx: CtxInterface) => void
private timeoutCallback: (ctx: CtxInterface) => void
private commands: Commands
private middlewares: any[]
private scenes: Scene[]
Expand All @@ -40,6 +45,10 @@ export default class Alice {
constructor(config: configInterface = {}) {
this.anyCallback = null
this.welcomeCallback = null
this.timeoutCallback = async (ctx) => {
await delay(DEFAULT_TIMEOUT_CALLBACK)
ctx.reply(DEFAULT_TIMEOUT_CALLBACK_MESSAGE)
}
this.commands = new Commands(config.fuseOptions || null)
this.middlewares = [aliceStateMiddleware()]
this.scenes = []
Expand Down Expand Up @@ -240,18 +249,31 @@ export default class Alice {
* При получении ответа от @handleRequestBody, результат
* отправляется обратно.
*/
public async listen(callbackUrl = '/', port = 80, callback?: () => void) {
public async listen(webhookPath = '/', port = 80, callback?: () => void) {
return new Promise((resolve) => {
const app = express()
app.use(express.json())
app.post(callbackUrl, async (req, res) => {
app.post(webhookPath, async (req, res) => {
if (this.config.oAuthToken) {
res.setHeader('Authorization', this.config.oAuthToken)
}
res.setHeader('Content-type', 'application/json')
const handleResponseCallback = (response) => res.send(response)

let responseAlreadySent = false
const handleResponseCallback = (response) => {
/* dont answer twice */
if (responseAlreadySent) {
return false
}
res.send(response)
responseAlreadySent = true
}
try {
return await this.handleRequestBody(req.body, handleResponseCallback)
const executors = [
this.handleRequestBody(req.body, handleResponseCallback),
await this.timeoutCallback(new Ctx({ req: req.body, sendResponse: handleResponseCallback })),
].filter(Boolean)
return await Promise.race(executors)
} catch (error) {
throw new Error(error)
}
Expand Down
4 changes: 3 additions & 1 deletion src/ctx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default class Ctx implements CtxInterface {
return reversedInterpolation(this.command.name, requestText)
}

public async reply(replyMessage) {
public async reply(replyMessage: string | {}): Promise<WebhookResponse> {
if (!replyMessage) {
throw new Error('Reply message could not be empty!')
}
Expand Down Expand Up @@ -103,4 +103,6 @@ export default class Ctx implements CtxInterface {

return replyMessage
}

public getDefaultRespons
}
1 change: 1 addition & 0 deletions src/types/ctx.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export interface CtxInterface {
replyBuilder: ReplyBuilder
buttonBuilder: ButtonBuilder

reply: (replyMessage: string | {}) => Promise<WebhookResponse>
sendResponse: (response: WebhookResponse) => void
enterScene: (sceneName: string) => void
leaveScene: () => void
Expand Down
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export const selectSession = (req) => req.session
export const selectSessionId = (req) => selectSession(req).session_id
export const selectUserId = (req) => selectSession(req).user_id
export const isFunction = (fn: () => void) => fn && typeof fn === 'function'
export const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))

export default {
getFiguresRegexp,
Expand Down

0 comments on commit d853700

Please sign in to comment.