Skip to content

Commit

Permalink
feat(method): proxy to VK.api when available
Browse files Browse the repository at this point in the history
Proxy API calls to the official VK JavaScript SDK when possible.

Related to #1.
  • Loading branch information
deltaidea committed May 5, 2016
1 parent 328b486 commit 9c07880
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 15 deletions.
35 changes: 20 additions & 15 deletions src/vk.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -77,22 +77,27 @@ module.exports =


method: ( methodName, params = {}, callback = -> ) ->
params.access_token = @accessToken
params.v = @version

new Promise ( resolve, reject ) =>
do retry = =>
@request
method: "POST"
url: "https://api.vk.com/method/#{methodName}"
params: params
callback: ({ error, response }) ->
if error?
if error.error_code is ERROR_TOO_MANY_REQUESTS
setTimeout retry, 300
else
callback error, response
reject error
wrappedCallback = ({ error, response }) ->
if error?
if error.error_code is ERROR_TOO_MANY_REQUESTS
setTimeout retry, 300
else
callback error, response
resolve response
reject error
else
callback error, response
resolve response

if window.VK?.api?
window.VK.api methodName, params, wrappedCallback

else
params.access_token = @accessToken
params.v = @version
@request
method: "POST"
url: "https://api.vk.com/method/#{methodName}"
params: params
callback: wrappedCallback
25 changes: 25 additions & 0 deletions test/vk.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ describe "vk", ->
fakeUrl = "https://api.vk.com/method/fake-method"

beforeEach ->
delete window.VK
vk.accessToken = "fake-token"
vk.version = "fake-version"

Expand Down Expand Up @@ -335,6 +336,30 @@ describe "vk", ->
done new Error "rejected!"


it "should proxy calls to VK.api when possible", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"

window.VK =
api: ( method, params, callback ) ->
method.should.equal fakeMethod
params.should.deep.equal
foo: "bar"

callback fakeData

vk.request = ->
done new Error "called vk.request!"

vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response

done()


describe "request", ->

fakeUrl = "https://api.vk.com/method/fake-method"
Expand Down

0 comments on commit 9c07880

Please sign in to comment.