Skip to content

Commit

Permalink
feat: improve alice.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
fletcherist committed Jul 1, 2018
1 parent 32e57b7 commit 4afa771
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 38 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,5 @@ typings/

package-lock.json
yarn.lock
inner
inner
sandbox
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
`yarn && npm run test && npm run dev`
> typescript-приложение соберётся в ./dist

### Создайте своё первое приложение

```javascript
Expand Down Expand Up @@ -237,6 +236,11 @@ const buyBtn = ctx.buttonBuilder
.get()
```

## 🔨 Сделано с помощью SDK

- [yandex-dialogs-whatis](https://github.com/popstas/yandex-dialogs-whatis)
Бот подскажет, что где находится, если вы перед этим расскажете ему об этом


# Contributors
Спасибо всем этим замечательным людям за библиотеку:
Expand Down
15 changes: 6 additions & 9 deletions src/alice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,16 @@ import { Sessions } from './sessions'
import { merge } from 'ramda'

import Scene from './scene'
import { ADDRCONFIG } from 'dns'
import Ctx from './ctx'

const Ctx = require('./ctx')

const {
import {
selectCommand,
selectSessionId,
isFunction,
} = require('./utils')
} from './utils'

const DEFAULT_ANY_CALLBACK = () => 'Что-то пошло не так. Я не знаю, что на это сказать.'
const DEFAULT_SESSIONS_LIMIT: number = 1000

export default class Alice {
private anyCallback: (ctx: Ctx) => void
Expand Down Expand Up @@ -94,7 +93,7 @@ export default class Alice {
const requestedCommandName = selectCommand(req)

/* clear old sessions */
if (this.sessions.length > (this.config.sessionsLimit || 1000)) {
if (this.sessions.length > (this.config.sessionsLimit || DEFAULT_SESSIONS_LIMIT)) {
this.sessions.flush()
}

Expand Down Expand Up @@ -207,7 +206,7 @@ export default class Alice {
* При получении ответа от @handleRequestBody, результат
* отправляется обратно.
*/
public async listen(callbackUrl = '/', port = 80, callback) {
public async listen(callbackUrl = '/', port = 80, callback: () => void) {
return new Promise((resolve) => {
const app = express()
app.use(express.json())
Expand Down Expand Up @@ -245,5 +244,3 @@ export default class Alice {
this.currentScene = null
}
}

module.exports = Alice
10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import replyBuilder from './replyBuilder'

const Alice = require('./alice')
import Alice from './alice'
const Scene = require('./scene')

// fp
Expand All @@ -21,3 +20,10 @@ export {
buttonBuilder,
replyBuilder,
}

module.exports = Alice
module.exports.Scene = Scene
module.exports.button = button
module.exports.reply = reply
module.exports.buttonBuilder = buttonBuilder
module.exports.replyBuilder = replyBuilder
2 changes: 1 addition & 1 deletion src/scene.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Alice from './alice'
const Commands = require('./commands')
const Command = require('./commands').Command
const Ctx = require('./ctx')
const Alice = require('./alice')

const selectCommand = (req) => req.request.command

Expand Down
2 changes: 1 addition & 1 deletion src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { merge } from 'ramda'
export default class Session {
public sessionId: string
public data: {}
constructor(sessionId, data = {}) {
constructor(sessionId: string, data = {}) {
if (!sessionId) { throw new Error('Cant create new session. Missed {sessionId}') }
this.sessionId = sessionId
this.data = data
Expand Down
6 changes: 3 additions & 3 deletions src/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ class Sessions {

public find(session) {
if (!session) { throw new Error('No session provided') }
return Object.values(this.sessions).find((_sess) => session === _sess)
return Object.values(this.sessions).find((sessionCandidate) => session === sessionCandidate)
}

public findById(sessionId) {
public findById(sessionId: string) {
if (this.sessions[sessionId]) {
return this.sessions[sessionId]
}
return null
}

public findOrCreate(sessionId) {
public findOrCreate(sessionId: string) {
if (this.findById(sessionId)) {
return this.findById(sessionId)
}
Expand Down
30 changes: 10 additions & 20 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ function extractTemplateTokenNames(template) {
return tokensObject
}

function searchFiguresInString(template, stringFigure: string) {
export function searchFiguresInString(template, stringFigure: string) {
const searchTemplateRegex = getFiguresRegexp(template)
const matched = searchTemplateRegex.exec(stringFigure)
return matched.filter(Boolean).slice(1)
}

function getFiguresRegexp(figure) {
export function getFiguresRegexp(figure) {
const searchTemplate = figure.replace(MATCH_REGEX, SEARCH_REGEX_STR)
return new RegExp(searchTemplate, 'ig')
}
Expand All @@ -32,29 +32,19 @@ function connectTokensWithFigures(tokens, figures) {
return res
}

function reversedInterpolation(template: string, string: string) {
export function reversedInterpolation(template: string, searchString: string) {
if (!template) { throw new Error('No template provided') }
if (!string) { throw new Error('No string provided') }
if (!searchString) { throw new Error('No searchString provided') }
const tokens = extractTemplateTokenNames(template)
const figures = searchFiguresInString(template, string)
const figures = searchFiguresInString(template, searchString)
return connectTokensWithFigures(tokens, figures)
}

const selectCommand = (req) => req.request.command
const selectSession = (req) => req.session
const selectSessionId = (req) => selectSession(req).session_id
const selectUserId = (req) => selectSession(req).user_id
const isFunction = (fn: () => void) => fn && typeof fn === 'function'

export {
getFiguresRegexp,
selectCommand,
selectSession,
selectSessionId,
selectUserId,
isFunction,
reversedInterpolation,
}
export const selectCommand = (req) => req.request.command
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 default {
getFiguresRegexp,
Expand Down

0 comments on commit 4afa771

Please sign in to comment.