client.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const io = require('socket.io-client');
  2. function path_join(...args) {
  3. return args.join('/').replace(/\/+/g, '/');
  4. }
  5. class Client {
  6. constructor(options) {
  7. if (options.socket_url) {
  8. this.socket = io(options.socket_url, {path: options.socket_path});
  9. }
  10. else {
  11. this.socket = io({path: options.socket_path});
  12. }
  13. this.username = null;
  14. this.room = options.room;
  15. }
  16. send(name, msg={}) {
  17. return new Promise((resolve, reject) => {
  18. this.socket.emit(name, msg, resolve);
  19. });
  20. }
  21. recv(name, callback) {
  22. this.socket.on(name, callback);
  23. }
  24. stop_recv(name, callback) {
  25. this.socket.removeListener(name, callback);
  26. }
  27. login(auth_data, callback=() => {}) {
  28. const auth_msg = Object.assign({room: this.room}, auth_data);
  29. this.socket.emit('authenticate', auth_msg, (function auth_handler(auth) {
  30. if (auth.error) {
  31. console.log('Auth error', auth.error);
  32. }
  33. this.username = auth.username;
  34. this.socket.once('connect', () => {
  35. this.socket.emit('authenticate', auth_msg, auth_handler.bind(this));
  36. });
  37. callback(auth);
  38. }).bind(this));
  39. }
  40. is_locked() {
  41. return this.send('get_locked');
  42. }
  43. lock() {
  44. return this.send('lock');
  45. }
  46. unlock() {
  47. return this.send('unlock');
  48. }
  49. get_entries(filter={}) {
  50. return this.send('get_all', filter);
  51. }
  52. add(type, data) {
  53. return this.send('add', {type, data});
  54. }
  55. remove() {
  56. return this.send('action', {
  57. action: 'remove',
  58. username: this.username,
  59. });
  60. }
  61. clear() {
  62. return this.send('clear');
  63. }
  64. action(type, data) {
  65. return this.send('action', Object.assign({action: type}, data));
  66. }
  67. get_staff_list() {
  68. console.log('get_staff_list');
  69. return this.send('get_staff_list');
  70. }
  71. check_in(username) {
  72. return this.send('check_in', {username});
  73. }
  74. check_out(username) {
  75. return this.send('check_out', {username});
  76. }
  77. }
  78. module.exports = Client;