API Reference(JavaScript, NodeJS)

※注1:Node.js SDKは最新バージョンに更新下さい。History APIは0.3.x以降でのみ利用できます。また、Node v4.0.0以上をお使いの場合は、インストール時にWebSocket関連モジュールでエラーが出ますが、Milkcocoaでは使っていないモジュールなので問題なくご利用頂けます。

The remove() API will be deprecated, please do not use remove API to a new project.

To maintain a high level of availability and provide superior quality of service, Milkcocoa limits the API call usage.

Retrieving Data (stream(), history())Data limit: 20,000 per Connection per minute
remove()Call limit: 30 per Connection per minute
send()Call limit: 240 per Connection per minute
Other MethodCall limit: 120 per Connection per minute

Milkcocoa Install

To use MilkCocoa API, write below script tag at your HTML file.

<script src="https://cdn.mlkcca.com/v0.6.0/milkcocoa.js"></script>

MilkCocoa

The MilkCocoa object is the main entry point for using this library. It manages establishing the connection, user login functionality, and exchanging data via the DataStore object.

MethodSummary
new MilkCocoa()accquire a MilkCocoa instance to establish a connection to the datastore, or publish information.
dataStore()instantiate a DataStore object to perform data transmission
addAccount()create a new login
authWithToken()ログインの処理を行います。
logout()process the logout action
user()get information about the existing logged in user

new MilkCocoa()

A connection is automatically established when creating a MilkCocoa instance. You can also accquire a DataStore object, and perform authentication functionality using this class.

Arguments
new MilkCocoa(host)
host
The MilkCocoa datastore host URL is passed as a string. The host and server have the format, app-id.mlkcca.com, where app-id is the unique identifier obtained when creating your application.
Return Value

When a correct AppID is passed, the return value is the host and a MilkCocoa instance is accquired with and a connection can be established.

Usage
var milkcocoa = new MilkCocoa('app-id.mlkcocoa.com');

dataStore()

Accquires a DataStore object. The DataStore object is used for datastore operation.

Arguments
dataStore(path)
path
You can assign the path to the datastore. Using `/` you can assign a datastore path relative to the root. Currently, it's possible to use non-existent paths; they are created on saving something to the datastore.
Return Value

The assigned DataStore object is returned

Usage
//create a DataStore object to handle 'message'
var messageDataStore = milkcocoa.dataStore('message');

//The DataStore child method can be used like this to access 'chat/message'.
var messageDataStore = milkcocoa.dataStore('chat').child('message');

addAccount()

With this method you can create new user login accounts. An account uses a 24-character hash value as the id.

Arguments
addAccount(email, password, options, callback)
email
pass the account email address
password
pass the account password
options
You can append extra account information using the JSON format.If you don't need any further information, you can pass the `null` value.
callback(err, user)
You can pass a callback function.
err

If there is an error during creation, the following errors are passed to the callback function

Error numberSummary
nullNo error: Registration completed successfully
'1'Invalid email address format
'2'Email address already used
user

When the login account creation is successful, the user object is passed as the second argument. In the failure case, the user value is `null`. The following properties are registered In the user data.

PropertyValue
emailregistered email address
optionthe additional options passed at the time of registration (in the case of no options, this is an empty object)
idThe user's unique 24 character identifier
Return Value

There is no return value.

Usage
milkcocoa.addAccount('sample@test.com', 'password', null, function(err, user) {
      switch (err) {
        case null:
          console.log('Success');
          break;
        case '1':
          console.log('Invalid Format');
          break;
        case '2':
          console.log('Already Exists');
          break;
      }
});

authWithToken()

ユーザーのログイン処理を行うメソッドです。

Arguments
authWithToken(token, callback)
token
ログインに使用するトークンを文字列で渡します。
callback(err, user)
コールバック関数を渡すことが出来ます。エラー処理や作成したユーザー情報の取得に利用してください。
err

アカウント追加に関するエラーを渡します。コールバック関数内でエラー処理をする際に活用してください。

エラー番号概要
nullログインが正常に終了しました。
invalid tokenトークンが無効です。
user

アカウントの追加に成功した場合にユーザーの情報がObject形式で渡されます。 失敗した場合はnullが渡されます。 ユーザー情報には以下のプロパティが登録されています。

Return Value

戻り値はありません。

Usage
milkcocoa.authWithToken(token, function(err, user) {
    switch(err){
    case null:
        console,log(user);
        break;
    case 'invalid token':
        console.log('トークンが無効です。');
        break;
    }
});

logout()

This is the method to perform user logout.

Arguments
logout(callback)
callback(err)
You can pass a callback function
err

For login errors, numeric values are passed. At present, there are no errors concerning logout in the frontend.

Error NumberSummary
nullNormal login successful
Return Value

There is no return value.

Usage
milkcocoa.logout();

user()

This method fetches the current logged-in user.

Arguments
user(callback)
callback(err, user)
You can pass a callback function.
err

The following errors are passed as numeric values:

Error NumberSummary
nullSuccessfully fetched user data
1There is no currently logged in user
user

in the account creation success case, the user data is passed as an Object. in the failure case, `null` is passed. The following properties are recorded in the user data Object.

PropertyValue
idUnique user identifier
Return Value

There is no return value.

Usage
milkcocoa.user(function(err, user) {
  // Fetch the data from the user with the same id as the current logged in user.
  milkcocoa.dataStore('users').child(user.id).get(function(data) {
  	console.log(data);
  });
});

DataStore

DataStore is an object for performing data exchange.

MethodSummary
push()append new data
set()edit data.
remove()delete data.
send()send data to the connected clients, without saving.
on()register datastore events.
off()cancel datastore events.
get()pass a specific ID to retrieve that data element.
stream()データストアからデータを順番に取得します。
child()you can fetch a child DataStore by its path.
parent()you can fetch a parent DataStore by its path.

push()

A method to append data to the datastore.(up to 4kb at once)

Arguments
push(object, onComplete, onError)
object
You can't set the id property on an object using the push method.
onComplete(err, datum)
you can assign a callback to be executed when the push has completed.
err

Error message when the push has failed.(default is null)

datum

ItemDescription
idPushed dada id
valuePushed data value
onError(err)
you can assign an error handler, it called when "permission denied" or "limit exceeded" error occured.
err

Error message

Return Value

returns the DataStore created when the push has been performed.

Usage
var chatDataStore = milkcocoa.dataStore('chat');
chatDataStore.push({
	content : 'Hello!'
});

milkcocoa.dataStore('chat').push({ 'content' : 'Hello!!!' }, function(err, pushed){
    console.log(pushed);
    /*
    {
        id: 'foo(Auto generated)',
        value: {
            content: 'Hello!!!'
        }
    }
    */
}, function(err) {
    //"Permission denied" or "limit exceeded"
});

set()

This method is for editing or appending to the datastore.

Arguments
set(id, data, onComplete, onError)
id
pass the id of datastore element you wish to edit/append as an argument
data
pass the data you wish to edit/append as an argument
onComplete(err, datum)
you can assign a callback to be executed when the set has completed.
err

Error message when the set has failed.(default is null)

datum

ItemDescription
idSet dada id
valueSet data value
onError(err)
you can assign an error handler, it called when "permission denied" or "limit exceeded" error occured.
err

Error message

Return Value

There is no return value.

Usage
// An example of editing data.
dataStore.set('id1', {content : 'update!'});

milkcocoa.dataStore('chat').set('testid', { 'content' : 'Hello!!!' }, function(err, set){
    console.log(set);
    /*
    {
        id: 'testid',
        value: {
            content: 'Hello!!!'
        }
    }
    */
}, function(err) {
    //"Permission denied" or "limit exceeded"
});

remove()

This method is to delete data from the datastore.

Arguments
remove(id, onComplete, onError)
id
pass the id of the datastore element you would like to delete.
onComplete(err, datum)
you can assign a callback to be executed when the remove has completed.
err

Error message when the remove has failed.(default is null)

datum

ItemDescription
idRemoved dada id
onError(err)
you can assign an error handler, it called when "permission denied" or "limit exceeded" error occured.
err

Error message

Return Value

There is no return value.

Usage
//a method to delete all data from the datastore.
dataStore.stream().next(function(err, data) {
  data.forEach(function(value) {
    dataStore.remove(value.id);
  });
});

milkcocoa.dataStore('chat').remove('test', function(err, removed){
    console.log(removed);
    /*
    {
        id: 'test'
    }
    */
}, function(err) {
    //"Permission denied" or "limit exceeded"
});

send()

Using this method you can send data without it being persisted. As a result, you can send data to clients registered as observers.

Arguments
send(object, onComplete, onError)
object
Pass the object you wish to send to the registered clients
onComplete(err, datum)
you can assign a callback to be executed when the send has completed.
err

Error message when the send has failed.(default is null)

datum

ItemDescription
valueSent dada value
onError(err)
you can assign an error handler, it called when "permission denied" or "limit exceeded" error occured.
err

Error message

Return Value

There is no return value.

Usage
// You can send data to a user subscribed to listen to an existing event.
// However, the value is not persisted in the datastore.
dataStore.send({
	content : 'Hello!'
});
milkcocoa.dataStore('chat').send({ 'content' : 'Hello!!!' }, function(err, sent){
    console.log(sent);
    /*
    {
        value: {
            content: 'Hello!!!'
        }
    }
    */
}, function(err) {
    //"Permission denied" or "limit exceeded"
});

on()

This is the datastore event registration method. You can even observe edit events for datastores.

Arguments
on(event, callback)
event
you can assign the event as a string.
TypeSummary
"push"datastore push event observation
"remove"datastore deletion event observation
"set"datastore send event observation
"send"datastore set event observation
callback(data)
You can set a callback to listen for events.
data

TypeSummary
erra string is set when there is an error
paththe path of the datastore pushed, setted or removed to
idthe datastore id pushed, setted or removed
valuethe value pushed or setted
Return Value

There is no return value.

Usage
dataStore.on('push', function(pushed) {
  console.log('pushed!', pushed.id, pushed.value);
});

dataStore.on('set', function(set) {
  console.log('set!', set.id, set.value);
});

dataStore.on('send', function(sent) {
  console.log('sent!', sent.value);
});

dataStore.on('remove', function(removed) {
  console.log('removed!', removed.id);
});

// the callback is called even when pushing data.
dataStore.push({
  message : 'I am pushing.''
});

off()

Cancel datastore event registration.

Arguments
off(event)
event
The registered event you want to cancel.
Return Value

There is no return value.

Usage
//you can cancel observing of events on a specific datastore started using `dataStore.on()`.
dataStore.off('push');

get()

This method is used to acquire data from the datastore.

Arguments
get(id, callback)
id
pass an id of datastore element.
callback(data)
You can set a callback.
data

This returns the data and its respective properties in the datastore.

Return Value

Returns the datastore element.

Usage
var user_data = {};
var user_name = 'example_tarou'

//In this example, user data is fetched from a datastore called 'users'
milkcocoa.dataStore('users').get(user_name, function(data) {
  user_data.profile = data.profile;
  user_data.status = data.status;
});

stream()

データストアからデータを取得するオブジェクトである、Streamオブジェクトを取得するメソッドです。

Arguments
stream()
There are no arguments
Return Value

Streamオブジェクトを返します。Streamオブジェクトに関してはこちらを御覧ください。

Usage
milkcocoa.dataStore('user').stream().sort('desc').next(function(err, data) {
    console.log(data);
});

child()

This is a method to fetch a child DataStore. If the assigned child does not exist, it is automatically created. You can accquire that child DataStore object.

Arguments
child(path)
path
You can assign the path to this datastore as a string. You can use Unix or Windows directory style formats.
Return Value

returns the DataStore object specified by the path.

Usage
var chatDataStore = milkcocoa.dataStore('chat');
//You can get child DataStore.
var messageDataStore = chatDataStore.child('message');

var userDataStore = chatDataStore.child('users');
userDataStore.child('jhon').set({email : 'jhon@test.com', sex : 'male'});

parent()

A method to fetch the parent DataStore.

Arguments
parent()
There are no arguments
Return Value

returns the parent DataStore object.

Usage
// get the parent datastore
var parent = dataStore.parent();

// You can perform event observation on the parent like this:
dataStore.parent().on("push", function(data) {
  console.log(data.id, data.value);
});

Stream

Streamオブジェクトはデータを取得するメソッドです。Streamオブジェクトを発行したDataStore以下にあるidをもつデータストアを取得することが出来ます。

MethodSummary
size()一回で取得するデータの個数を決めます。
sort()指定した要素でデータを降順にソートします。
next()データストアからデータの取得を行います。

size()

一回で取得するデータの個数を決めるためのメソッドです。

Arguments
size(num)
num
データサイズを指定します。
Return Value

条件が追加されたStreamオブジェクトを返します。

Usage
//pushした順番に対して降順で取得
milkcocoa.dataStore('user').stream().size(10).next(function(err, data) {
    console.log(data)
});

sort()

指定した要素でデータをソートする条件を追加するメソッドです。

Arguments
sort(mode)
mode
ソートの昇順、降順を指定します。
タイプ概要
"asc"昇順でソートします。
"desc"降順でソートします。
Return Value

条件が追加されたStreamオブジェクトを返します。

Usage
//pushした順番に対して降順で取得
milkcocoa.dataStore('user').stream().sort('desc').done(function(data) {
    console.log(data)
});

next()

データの取得を開始するメソッドです。追加された検索条件を元にデータストアからデータを取得し、指定したコールバック関数に渡すことが出来ます。

Arguments
next(callback)
callback(data)
データの取得が完了した際に呼ばれるコールバックを指定します。コールバックの引数に取得したデータを含むオブジェクトが渡されます。
data

データを配列形式で取得することが出来ます。

Return Value

戻り値はありません。

Usage
dataStore.stream().next(function(err, data) {
    console.log(data);
});