1.0.5 • Published 3 years ago

ciri_cloud_client v1.0.5

Weekly downloads
3
License
ISC
Repository
gitlab
Last release
3 years ago

ciri_cloud_client

CIRI-Cloud的JS客户端, 前后端通用

调试

npm install

# on *NIX
# export DEBUG=ciri

# on Windows
set DEBUG=ciri

npm run test

安装使用

npm i git+http://gitlab.mycyclone.com/cyclone-chatbot-dev/ciri_cloud_client#v1.0.4

然后就像下面这么用, 更多用法见 tests/flow.test.ts

import { CIRICloudClient, createCIRICloudClient, Interaction, InteractionUpdateRequest } from 'ciri_cloud_client'
import { once } from 'events'
import assert from 'assert'

const HOST = '10.10.10.217'
const PORT = 8003

/**
 * 测试人机交互任务的简单流程
 *
 * 1) workflow1发送任务给test
 * 2) test收到任务, 完成(done)
 * 3) workflow1收到test的完成任务的提示
 *    1) websocket收到完成的事件
 *    2) get方法返回正确的结果
 */
async function testHappyPath () {
  console.log('testing happy path...')
  let hostOptions: any = {
    host: HOST,
    port: PORT,
  }
  let user1: CIRICloudClient | null = null
  let wf1: CIRICloudClient | null = null
  try {
    user1 = await createCIRICloudClient({
      ...hostOptions,
      role: 'user',
      username: 'test',
      password: 'test'
    })
    wf1 = await createCIRICloudClient({
      ...hostOptions,
      role: 'workflow',
      username: 'workflow1'
    })

    // 1. workflow创建人机交互任务
    const interactionId = await wf1.interaction.create({
      ownerId: 'test',
      payload: { omit: true },
      deadline: +new Date() + 3600 * 1000
    })

    // 2. 用户监听message事件, 发现有interaction的事件的时候, done之
    user1.interaction.on('message', (msg: Interaction) => {
      const request: InteractionUpdateRequest = {
        id: msg.id,
        status: 'done',
        payload: { updated: true }
      }
      if (user1)
        user1.interaction.update(request)
          .catch(console.error)
          .then(() => {
            // 我们100ms以后更新一下结果, 处理太快的话测试脚本会有问题
            setTimeout(() => {if (user1) user1.emit('done')}, 100)
          })
    })

    let res = await Promise.allSettled([once(user1, 'done'), once(wf1.interaction, 'message')])

    // 3. workflow1确认收到完成消息
    // 3.1 websocket事件
    let msg = res[1].status === 'fulfilled' && res[1].value[0] as Interaction
    assert(msg, `msg should exists`)
    if (msg) {
      assert(msg.status === 'done', `status not updated: ${msg}`)
      assert(msg.payload.updated, `payload not updated: ${msg}`)
    }
    // 3.2 http polling
    msg = await wf1.interaction.get(interactionId)
    if (msg) {
      assert(msg.payload.updated, `payload not updated: ${msg}`)
      assert(msg.status === 'done', `status not updated: ${msg}`)
    }

  } catch (error) {
    throw error
  } finally {
    if (user1)
      await user1.close()
    if (wf1)
      await wf1.close()
  }

  console.log('...pass')
}

async function testAll () {
  await testHappyPath()
}

testAll().catch((error) => { console.error(`最外层捕获 ${error.stack}`) })