Skip to content

Commit

Permalink
fix: jsdoc & comments
Browse files Browse the repository at this point in the history
  • Loading branch information
fletcherist committed Jul 30, 2018
1 parent 7d16620 commit 03a7e20
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 104 deletions.
127 changes: 63 additions & 64 deletions src/alice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,49 +71,49 @@ export default class Alice implements IAlice {
eventEmitter.subscribe(event, callback)
}

/*
* Attach alice middleware to the application
* @param {Function} middleware - function, that receives {context}
* and makes some modifications with it.
*/
/**
* Attach alice middleware to the application
* @param {Function} middleware - function, that receives {context}
* and makes some modifications with it.
*/
public use(middleware: (IContext: IContext) => IContext): void {
if (!isFunction(middleware)) {
throw new Error('Any middleware could only be a function.')
}
this.middlewares.push(middleware)
}

/*
* Set up the command
* @param {string | Array<string> | regex} name — Trigger for the command
* @param {Function} callback — Handler for the command
*/
/**
* Set up the command
* @param {string | Array<string> | regex} name — Trigger for the command
* @param {Function} callback — Handler for the command
*/
public command(name: ICommand, callback: (IContext) => void) {
this.commands.add(name, callback)
}

/*
* Стартовая команда на начало сессии
*/
/**
* Стартовая команда на начало сессии
*/
public welcome(callback: (IContext) => void): void {
this.welcomeCallback = callback
}

/*
* Если среди команд не нашлось той,
* которую запросил пользователь,
* вызывается этот колбек
*/
/**
* Если среди команд не нашлось той,
* которую запросил пользователь,
* вызывается этот колбек
*/
public any(callback: (IContext) => void): void {
this.anyCallback = callback
}

/*
* Match the request with action handler,
* compose and return a reply.
* @param {Object} req — JSON request from the client
* @param {Function} sendResponse — Express res function while listening on port.
*/
/**
* Match the request with action handler,
* compose and return a reply.
* @param {Object} req — JSON request from the client
* @param {Function} sendResponse — Express res function while listening on port.
*/
public async handleRequestBody(req, sendResponse): Promise<any> {
/* clear old sessions */
if (this.sessions.length > (this.config.sessionsLimit || DEFAULT_SESSIONS_LIMIT)) {
Expand All @@ -124,17 +124,17 @@ export default class Alice implements IAlice {
const sessionId = selectSessionId(req)
const session = this.sessions.findOrCreate(sessionId)

/*
* Initializing context of the request
*/
/**
* Initializing context of the request
*/
const ctxDefaultParams = {
req,
session,
sendResponse: sendResponse || null,
/*
* if Alice is listening on express.js port, add this server instance
* to the context
*/
/**
* if Alice is listening on express.js port, add this server instance
* to the context
*/
server: this.server || null,
scenes: this.scenes,
middlewares: this.middlewares,
Expand All @@ -159,10 +159,10 @@ export default class Alice implements IAlice {
return scene.name === session.getData('currentScene')
})

/*
* Checking whether that's the leave scene
* activation trigger
*/
/**
* Checking whether that's the leave scene
* activation trigger
*/
if (matchedScene) {
if (await matchedScene.isLeaveCommand(context)) {
const sceneResponse = await matchedScene.handleSceneRequest(
Expand All @@ -185,9 +185,9 @@ export default class Alice implements IAlice {
}
}
} else {
/*
* Looking for scene's activational phrases
*/
/**
* Looking for scene's activational phrases
*/
let matchedScene = null
for (const scene of this.scenes) {
const result = await scene.isEnterCommand(context)
Expand All @@ -211,31 +211,31 @@ export default class Alice implements IAlice {
}

const requestedCommands = await this.commands.search(context)
/*
* Если новая сессия, то запускаем стартовую команду
*/
/**
* Если новая сессия, то запускаем стартовую команду
*/
if (req.session.new && this.welcomeCallback) {
/*
* Patch context with middlewares
*/
/**
* Patch context with middlewares
*/
if (this.welcomeCallback) {
return await this.welcomeCallback(context)
}
}
/*
* Команда нашлась в списке.
* Запускаем её обработчик.
*/
/**
* Команда нашлась в списке.
* Запускаем её обработчик.
*/
if (requestedCommands.length !== 0) {
const requestedCommand: ICommand = requestedCommands[0]
context.command = requestedCommand
return await requestedCommand.callback(context)
}

/*
* Такой команды не было зарегестрировано.
* Переходим в обработчик исключений
*/
/**
* Такой команды не было зарегестрировано.
* Переходим в обработчик исключений
*/
if (!this.anyCallback) {
throw new Error(
[
Expand All @@ -247,9 +247,9 @@ export default class Alice implements IAlice {
return await this.anyCallback(context)
}

/*
* Same as handleRequestBody, but syntax shorter
*/
/**
* Same as handleRequestBody, but syntax shorter
*/
public async handleRequest(
req: WebhookRequest,
sendResponse?: (res: WebhookResponse) => void
Expand All @@ -267,15 +267,14 @@ export default class Alice implements IAlice {
this.timeoutCallback(new Context({ req, sendResponse }))
})
}
/*
* Метод создаёт сервер, который слушает указанный порт.
* Когда на указанный URL приходит POST запрос, управление
* передаётся в @handleRequestBody
*
* При получении ответа от @handleRequestBody, результат
* отправляется обратно.
*/
/**
* Метод создаёт сервер, который слушает указанный порт.
* Когда на указанный URL приходит POST запрос, управление
* передаётся в @handleRequestBody
*
* При получении ответа от @handleRequestBody, результат
* отправляется обратно.
*/
public async listen(webhookPath = '/', port = 80, callback?: () => void) {
return new Promise(resolve => {
const app = express()
Expand Down
1 change: 0 additions & 1 deletion src/buttonBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,3 @@ export default class ButtonBuilder {
return this
}
}

18 changes: 10 additions & 8 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,10 @@ export default class Context implements IContext {
}

private _createReply(replyMessage): WebhookResponse {
/*
* Если @replyMessage — string,
* то заворачиваем в стандартную форму.
*/
/**
* Если @replyMessage — string,
* то заворачиваем в стандартную форму.
*/
if (typeof replyMessage === 'string') {
replyMessage = this.replyBuilder
.text(replyMessage)
Expand All @@ -162,11 +162,13 @@ export default class Context implements IContext {
}

private _sendReply(replyMessage: WebhookResponse): any {
if (this._isReplied) return
if (this._isReplied) {
return
}
this._isReplied = true
/*
* That fires when listening on port.
*/
/**
* That fires when listening on port.
*/
if (typeof this.sendResponse === 'function') {
eventEmitter.dispatch(EVENT_MESSAGE_SENT, {
data: replyMessage.response.text,
Expand Down
21 changes: 0 additions & 21 deletions src/middlewares/aliceStateMiddleware.ts

This file was deleted.

13 changes: 6 additions & 7 deletions src/scene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ export default class Scene extends Alice {
/* enter, leave, etc */
}

/*
* Trigger to activate the scene
*/
/**
* Trigger to activate the scene
*/
public enter(name, callback) {
if (!name) {
throw new Error('Enter command name is not specified')
Expand All @@ -44,9 +44,9 @@ export default class Scene extends Alice {
this.enterCommand.add(name, callback)
}

/*
* Trigger to leave the scene
*/
/**
* Trigger to leave the scene
*/
public leave(name, callback) {
if (!name) {
throw new Error('Leave command name is not specified')
Expand Down Expand Up @@ -109,4 +109,3 @@ export default class Scene extends Alice {
return Promise.resolve()
}
}

6 changes: 3 additions & 3 deletions src/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ class Sessions {
return false
}

/*
* Remove all sessions
*/
/**
* Remove all sessions
*/
public flush() {
this.sessions = {}
}
Expand Down

0 comments on commit 03a7e20

Please sign in to comment.