Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const WebSocket = require('ws')
- const SHA256 = require('crypto-js/sha256')
- const EJSON = require('ejson')
- const { rocketTypes, resolveTypes } = require('./types')
- const { hashPassword, generateId } = require('./utils')
- const DDP = require('./ddp')
- class Socket {
- constructor(url, ddp) {
- this.url = url
- this.ddp = ddp
- }
- connection() {
- if (this.wss) {
- return
- }
- this.wss = new WebSocket(this.url, null)
- this.wss.onopen = this.onOpen.bind(this)
- this.wss.onerror = this.onError.bind(this)
- this.wss.onclose = this.onClose.bind(this)
- this.wss.onmessage = this.onMessage.bind(this)
- this.ddp.subscribe(rocketTypes.PING, () => {
- this.send({ msg: rocketTypes.PONG }, true)
- })
- }
- async onOpen() {
- this.send({ msg: rocketTypes.CONNECTION, version: '1', support: ['1'] }, true)
- const data = await this.loginWithPassword('dmitry.shelomanov', '123456789qwert')
- this.ddp.emit(resolveTypes.LOGIN, data)
- }
- onError(error) {
- console.log('error', error)
- }
- onMessage({ data }) {
- data = JSON.parse(data)
- this.ddp.emit(data.id || data.msg, data)
- }
- loginWithPassword(username, password) {
- return this.call(rocketTypes.LOGIN, {
- user: { username },
- password: hashPassword(password),
- })
- }
- onClose(reason) {
- console.log('onClose', reason)
- }
- send(obj, ignore) {
- return new Promise((resolve, reject) => {
- const id = generateId()
- this.wss.send(JSON.stringify({ ...obj, id }))
- if (ignore) {
- resolve(true)
- return
- }
- this.ddp.subscribe(id, (data) => {
- this.ddp.removeListener(id)
- return data.error
- ? reject(data.error)
- : resolve({ id, ...data })
- })
- })
- }
- call(method, ...params) {
- return this.send({ msg: 'method', method, params })
- }
- }
- const s = new Socket('wss://chat.unitemp.ru/websocket', DDP)
- s.connection()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement