i-im-handler.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * 由于JavaScript没有接口的概念,所以我编写了这个IM基类
  3. * 将你自己的IM的实现类继承这个类就可以了
  4. * 我把IM通信的常用方法封装在这里,
  5. * 有些实现了具体细节,但有些没实现,是作为抽象函数,由子类去实现细节,这点是大家需要注意的
  6. */
  7. import ImApi from './../../../apis/im'
  8. export default class IIMHandler {
  9. constructor() {
  10. this._isLogin = true;
  11. this._msgQueue = [];
  12. this._receiveListener = [];
  13. }
  14. /**
  15. * 创建IM连接
  16. * @param options 传入你建立连接时需要的配置信息,比如url
  17. */
  18. createConnection({options}) {
  19. // 作为抽象函数
  20. }
  21. /**
  22. * 发送消息
  23. * @param content 需要发送的消息,是一个对象,如{type:'text',content:'abc'}
  24. */
  25. sendMsg({content}) {
  26. return new Promise((resolve, reject) => {
  27. if (this._isLogin) {
  28. return this._sendMsgImp({content, success: resolve, fail: reject});
  29. } else {
  30. this._msgQueue.push({content, resolve, reject});
  31. }
  32. });
  33. }
  34. newFriendSendMsg ({ content }) {
  35. return ImApi.addFriend(content.toId).finally(() => {
  36. this.sendMsg({ content })
  37. })
  38. }
  39. /**
  40. * 消息接收监听函数
  41. * @param listener
  42. */
  43. setOnReceiveMessageListener({listener}) {
  44. this._receiveListener.push(listener);
  45. }
  46. removeOnReceiveMessageListener ({listener}) {
  47. for (var i = 0; i < this._receiveListener.length; i++) {
  48. var item = this._receiveListener[i]
  49. if (item === listener) {
  50. this._receiveListener.splice(i, 1)
  51. return
  52. }
  53. }
  54. }
  55. closeConnection() {
  56. // 作为抽象函数
  57. }
  58. _sendMsgImp({content, success, fail}) {
  59. // 作为抽象函数
  60. }
  61. }