Code Monkey home page Code Monkey logo

soracom's Introduction

soracom

SORACOM API client for Node.js.

Install

$ npm install soracom

Usage

Authenticate with a pair of email and password, then retrieve your operator information.

var Soracom = require('soracom');
var soracom = new Soracom({ email: 'email', password: 'password' });
soracom.post('/auth', function(err, res, auth) {
  if (!error) {
  	console.log(auth); // {apiKey: "api_key", token: "token", operatorId: "operator_id"}
  	soracom.defaults(auth);
    soracom.get('/operators/:operatorId', function(err, res, operator) {});
  }
});

You can also specify your credentials directly on instantiation.

var Soracom = require('soracom');
var soracom = new Soracom({
  apiKey: 'api_key',
  token: 'token',
  operatorId: 'operator_id'
});
soracom.get('/operators/:operatorId', function(err, res, operator) {})

The given apiKey and token are automatically set to HTTP header on subsequent requests. The rest of properties, in the above case operatorId, are used as any of default request path, query or request body.

Examples

All examples below assume that you already set the following credentials to the soracom object.

var Soracom = require('soracom');
soracom = new Soracom();
soracom.defaults({
  apiKey: 'api_key',
  token: 'token',
  operatorId: 'operator_id'
});

Operator

Get operator.

soracom.get('/operators/:operatorId', function(err, res, body) {});

Create operator.

soracom.post('/operators', function(err, res, body) {});

Subscriber

List subscribers with speed class s1.minimum.

soracom.get('/subscribers', { speed_class_filter: 's1.minimum' }, function(err, res, body) {});

Get subscriber.

soracom.get('/subscriber/:imsi', { ismi: '123456789012345' }, function(err, res, body) {});

Activate subscriber.

soracom.post('/subscribers/:imsi/activate', { imsi: '123456789012345' }, function(err, res, body) {});

Deactivate subscriber.

soracom.post('/subscribers/:imsi/deactivate', { imsi: '123456789012345' }, function(err, res, body) {});

Insert tags to subscriber.

Note if the type of request body is an array, you cannot pass any other properties (i.e. imsi) on the same request. To workaround this, you need to call soracom.defaults({ imsi: '123456789012345'}) beforehand, or you can just call function with static path soracom.put('/subscribers/123456789012345/tags')).

soracom.defaults({ imsi: '123456789012345' });
soracom.put('/subscribers/:imsi/tags', [{ tagName: 'foo', tagValue: 'bar'}], function(err, res, body) {});

Delete tag from subscriber.

soracom.delete('/subscribers/:imsi/tags/:tagName', { imsi: '123456789012345', tagName: 'foo' }, function(err, res, body) {});

Stats

Get air usage report of subscriber.

soracom.get('/stats/air/subscribers/:imsi', {
  imsi: '123456789012345',
  from: 1443657600,
  to: 1446335999,
  period: 'day'
}, function(err, res, body) {});

API

var soracom = new Soracom(obj);

Create a Soracom instance that can be used to make reqeusts to SORACOM's APIs.

If authenticating with user account, obj should look like:

new Soracom({ email: '[email protected]', password: 'superStrongP@ssw0rd' });

If authenticating with credentials, obj should look like:

new Soracom({ apiKey: 'api_key', token: 'very_long_string_token' });

soracom.defaults(obj);

Set given object properties to either default http headers or default request path, query or request body.

If the key of property is either apiKey or token, then its value is set to default headers and deleted from original object. The headers are mapped like below:

headers = {
  'X-Soracom-API-Key': apiKey,
  'X-Soracom-Token': token
};

soracom.get(path, [params], callback);

GET any of the REST API endpints.

path

The endpoint to hit. When path contains special tag starts with :, then that tag should be treated as variable. If there is property with same name as that variable existed in the given param, then the tag is replaced with that value.

Example 1:

var soracom = new Soracom({ apiKey: 'api_key', token: 'token', operatorId: 'OP1234567890' });
soracom.get('/operators/:operatorId', callback);
// The operatorId is exracted from default params, so the endpoint will be "/operators/OP1234567890"

Example 2:

var soracom = new Soracom({ apiKey: 'api_key', token: 'token' });
soracom.get('/subscriber/:imsi', { imsi: '123456789012345' }, callback);
// The imsi is exracted from given params in a same function call, so the endpoint will be "/subscribers/123456789012345"

params

(Optional) parameters for request.

callback

The callback argument gets 3 arguments function (error, response, body):

  • error: An error object when applicable
  • response: An http.IncomingMessage object
  • body: JSON.parse()ed response body

soracom.post(path, [params], callback);

Same as get(), but set method to POST.

soracom.put(path, [params], callback);

Same as get(), but set method to PUT.

soracom.delete(path, [params], callback);

Same as get(), but set method to DELETE.

Testing

Currently we have two test scripts, helper.js and e2e.js. helper.js is an unit test for lib/helper.js while e2e.js is an integration test using lib/soracom.js to execute real API access. By default e2e.js is disabled (it's simply marked as skip by mocha).

To run the unit test:

$ npm test

You can also run integration test by modifying the line in e2e.js.

describe.skip('e2e', function() { // remove .skip from this line.

Then add your accout info to test/account.json.

$ echo '{"email": "email_address", "password": "password"}' > test/account.json

Finally run the test command, same as unit test.

$ npm test

License

MIT

soracom's People

Contributors

tatsuya avatar

Stargazers

Keenan Nicholson avatar kyokucho1989 avatar masato-ka avatar Jimmy avatar Sunil Shah avatar Ryosuke Horie avatar Akio Katayama avatar Haga Satoshi avatar Yuji Tokuda avatar  avatar  avatar Yoshihiro Furukawa avatar moto avatar  avatar

Watchers

Akio Katayama avatar Alexis Susset avatar

soracom's Issues

POSTリクエストのBODY部に不要な過去のBODYが混在する。

例えば以下のリクエストを実行した場合、1回目リクエストの内容が2回目リクエストのないように含まれて送信されます。

const Soracom = require('soracom');
const soracom = new Soracom();
const authKetId= xxxx
const authKey= xxxx
//1回目リクエスト
soracom.post("/auth",{authKeyId:_authKeyId, authKey:_authKey},function(err,req,body){
       soracom.defaults({
                    apiKey: body['apiKey'],
                    token: body['token']
        });
});

//2回目リクエスト 1回目リクエストの内容が合わせて送信される。
soracom.post("/subscribers/:imsi/update_speed_class", {imsi:_imsi, speedClass:speed},
                    function(err,req,body){
                    resolve(body);
})

以下のメソッドで、各リクエストのbodyの内容をSoracom クラスのdefaultParamsでキャッシュしているため発生する事象です。
https://github.com/tatsuyaoiw/soracom/blob/69271a873ca04300d19fd727ef4d97f916e0f70a/lib/helper.js#L35

現在のところ、Subscriber 系のAPIではbodyに定義されていないパラメータが入っていても、リクエストを正常に受け付けますが、以下のようなリクエストでグループを作成しようとするとSORACOM 側のAPIでエラーが発生します。

soracom.post("/auth",{authKeyId:_authKeyId, authKey:_authKey},function(err,req,body){
       soracom.defaults({
                    apiKey: body['apiKey'],
                    token: body['token']
        });
});

soracom.post("/groups",{tags:{name:groupName}}, function(err,req,body){
    //SORACOM APIからauthKeyが未定義というエラーが返ってくる。
});

/*
期待すべきbody
{
    tags:{name:"groupName"}
}

実際のbody
{
    authKeyId:_authKeyId, 
    authKey:_authKey,
    tags:{name:"groupName"}
}
*/

以上、ご報告させていただきます。

Can't insert/update tags

This operation requires an array passed as request body so we cannot pass imsi as a property of params at the same time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.