-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsonglocator-api-client.coffee
61 lines (49 loc) · 1.55 KB
/
songlocator-api-client.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
###
songlocator-base
2013 (c) Andrey Popp <[email protected]>
###
((root, factory) ->
if typeof exports == 'object'
SongLocator = require 'songlocator-base'
module.exports = factory(SongLocator)
else if typeof define == 'function' and define.amd
define (require) ->
SongLocator = require 'songlocator-base'
root.SongLocator.API = factory(SongLocator)
else
root.SongLocator.API = factory(window.SongLocator)
) this, ({BaseResolver, extend}) ->
class Client extends BaseResolver
constructor: (options) ->
this.options = options
this.queue = []
this.initSocket()
initSocket: ->
this.isOpenned = false
this.sock = new WebSocket(this.options.uri)
this.sock.onopen = =>
this.isOpenned = true
if this.queue.length > 0
for {method, data} in this.queue
this.call(method, data)
this.queue = []
this.sock.onerror = => this.initSocket()
this.sock.onmessage = this.onMessage.bind(this)
onMessage: (e) ->
data = try
JSON.parse e.data
catch e
undefined # TODO: logging
return unless data?.qid? and data?.results?
this.results(data.qid, data.results)
call: (method, data) ->
if this.isOpenned
data.method = method
this.sock.send JSON.stringify data
else
this.queue.push {method, data}
search: (qid, query) ->
this.call 'search', {qid, query}
resolve: (qid, title, artist, album) ->
this.call 'resolve', {qid, title, artist, album}
{Client}