From 9c0788056ba87ba76bbbcadf85a284c545009ab1 Mon Sep 17 00:00:00 2001 From: Nikita Litvin Date: Thu, 5 May 2016 23:40:07 +0500 Subject: [PATCH] feat(method): proxy to `VK.api` when available Proxy API calls to the official VK JavaScript SDK when possible. Related to #1. --- src/vk.coffee | 35 ++++++++++++++++++++--------------- test/vk.coffee | 25 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/src/vk.coffee b/src/vk.coffee index 95a147c..b417557 100644 --- a/src/vk.coffee +++ b/src/vk.coffee @@ -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 diff --git a/test/vk.coffee b/test/vk.coffee index f9a2932..019e284 100644 --- a/test/vk.coffee +++ b/test/vk.coffee @@ -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" @@ -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"