Skip to content
This repository has been archived by the owner on Aug 3, 2020. It is now read-only.

Commit

Permalink
feat: add new option: "protocol", ensure that base url contains a pro…
Browse files Browse the repository at this point in the history
…tocol field

Option "baseUrl" now takes precedence over option "host" when specifying the remote CQHTTP
server.

fix #32
  • Loading branch information
MomoCow committed Oct 15, 2018
1 parent ff10224 commit ae1881d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
2 changes: 2 additions & 0 deletions cq-websocket.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ export enum WebsocketState {
export interface CQRequestOptions {
timeout: number
}
type WebSocketProtocol = "http:" | "https:" | "ws:" | "wss:"
export interface CQWebSocketOption {
access_token: string
enableAPI: boolean
enableEvent: boolean
protocol: WebSocketProtocol
host: string
port: number
baseUrl: string
Expand Down
31 changes: 26 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,21 @@ const WebsocketState = {
DISABLED: -1, INIT: 0, CONNECTING: 1, CONNECTED: 2, CLOSING: 3, CLOSED: 4
}

const WebSocketProtocols = [
'https:',
'http:',
'ws:',
'wss:'
]

class CQWebsocket extends $Callable {
constructor ({
// connectivity configs
host,
port,
protocol = 'ws:',
host = '127.0.0.1',
port = 6700,
access_token: accessToken = '',
baseUrl = '127.0.0.1:6700',
baseUrl,

// application aware configs
enableAPI = true,
Expand All @@ -44,14 +52,27 @@ class CQWebsocket extends $Callable {
} = {}) {
super('__call__')

///*****************/
// poka-yoke 😇
///*****************/
protocol = protocol.toLowerCase()
if (protocol && !protocol.endsWith(':')) protocol += ':'
if (
baseUrl &&
WebSocketProtocols.filter(proto => baseUrl.startsWith(proto + '//')).length === 0
) {
baseUrl = `${protocol}//${baseUrl}`
}


///*****************/
// options
///*****************/

this._token = String(accessToken)
this._qq = parseInt(qq)
this._atme = new $CQAtTag(this._qq)
this._baseUrl = host ? `${host}${port ? `:${port}` : '' }` : baseUrl
this._baseUrl = baseUrl || `${protocol}//${host}:${port}`

this._reconnectOptions = {
reconnection,
Expand Down Expand Up @@ -326,7 +347,7 @@ class CQWebsocket extends $Callable {
if ([ WebsocketState.INIT, WebsocketState.CLOSED ].includes(this._monitor[_label].state)) {
const tokenQS = this._token ? `?access_token=${this._token}` : ''

let _sock = new $WebSocket(`ws://${this._baseUrl}/${_label.toLowerCase()}${tokenQS}`, undefined, this._wsOptions)
let _sock = new $WebSocket(`${this._baseUrl}/${_label.toLowerCase()}${tokenQS}`, undefined, this._wsOptions)

if (_type === WebsocketType.EVENT) {
this._eventSock = _sock
Expand Down

0 comments on commit ae1881d

Please sign in to comment.