Yodata JavaScript Client
Use this JavaScript library to access the Yodata platform with your browser, node.js, or Meteor based applications. All API calls accept and return JSON objects.
Requirements
At the moment, the only requirement to use this library is jQuery (tested with v1.11.1) with a browser based app. There are no required modules for node.js or Meteor apps.
Setup
Browser Based
- Manually copy the
yodata.client.js
file to your website file structure. - Create a script tag that references the proper location of the file. This script tag should be below the script tag for the jQuery library.
- Download the
yodata.client.ui.js
file from the yodata-client-ui-js project and follow the instructions to configure the login button. - The
YDClient
object can be accessed through the client UI library's api
property.
Node.js
- At the root directory of your node application, install the package at the command line by typing
npm i yodata-client-js
, or add the "yodata-client-js": "0.0.18"
(using the current version number) to the dependencies
node your package.json file and run npm install
.
Meteor
- At the command line of your Meteor app's root folder type
meteor add bshamblen:yodata-client
and hit enter. Please refer to the meteor-yodata-client Github repository for Meteor specific examples.
Examples
Browser Based
var ydClientUi = null;
$(document).ready(function() {
ydClientUi = new YDClientUi();
ydClientUi.onAuthStateChanged(function() {
if(ydClientUi.isAuthenticated()) {
ydClientUi.api.userProfile(function(err, results) {
if (err || !results) {
ydClientUi.logout();
} else {
$('#welcomeMessage').html('Welcome <strong>' + results.profile.name + '</strong>');
reloadTasks();
}
});
} else {
}
});
}
function reloadTasks() {
var options = {
limit: 100,
sort: {createdAt: -1}
}
ydClientUi.api.find('yodata.task', options , function(err, results) {
if (err) {
} else {
}
});
}
Node.js
var YDClient = require('yodata-client-js');
var client = new YDClient({ authToken: 'an auth token that was returned by the client side ui library.'});
var options = {
limit: 100,
sort: {createdAt: -1}
}
client.find('yodata.task', options , function(err, results) {
if (err) {
} else {
}
});
Callback Functions
The Yodata JavaScript client uses the standard arguments for a JavaScript async callback function. All of your callback functions for each of the methods below should accept both an error and a result object:
function(err, results) {
if (err) {
} else {
}
}
Authentication
Two forms of authentication are currently supported, Auth Token and Client ID/Client Secret.
Auth Token
Auth tokens are generated in one of two ways:
- Through the OAuth 2 login process, which allows a user to grant your app permissions to specific collections.
- A user can manually issue an auth token in the Datastores section of Yodata.io, granting your application permissions to the collections that are "required" by your application in the Applications section of Yodata.io. When a user grants your app an auth token in this manner you'll recieve a system notification (email or web based). Typlically this is only used when one application is granting access to another application, for the purposes of server to server access.
This form of authentication is handled automatically by the Yodata Client UI library. If you intend to write your own OAuth UI, or if you're executing commands server side, the following contructor arguments should be used.
var client = new YDClient({ authToken: 'a valid auth token...' });
Client ID/Client Secret
This form of authentication allows your application unlimited access to any collection (no scopes), for the purposes of storing application level data, not user level data. Your application's Client ID and Client Secret can be located in the Applications section of Yodata.io. To use this form of authentication, you'll need to attach a datastore to your application.
Since this form of authentication uses your application's "client secret", this form of authentication is only supported for server side access (node.js/Meteor.js). You should never publish your client secret on the internet (in your HTML or JavaScript).
var client = new YDClient({
clientId: 'The Client ID for your app',
clientSecret: 'The Client Secret for your app'
});
YDClient Methods
- insert - Inserts a new document into a collection.
- save - Updates an existing, complete, unpopulated document.
- update - Updates only the specified properties of an existing document.
- remove - Deletes one or more existing documents.
- findOne - Finds exactly one document, with the given options.
- findById - Finds exactly one document, with the given objectId.
- find - Returns a list of documents. Includes metadata for paging.
- distinct - Returns a distinct list of values for the given fields in a collection.
- count - Returns the number of records that match the given search criteria.
- aggregate - Runs a mongodb aggregate query against the collection.
- userProfile - Returns profile information about the current oauth token.
- uploadFile - Upload a file. Files can be public or private.
- generateDownloadUrlForPrivateFileById. - Generate a download URL for a private file.
YDClient.insert (modelId, doc, [options], callback)
required scope: POST:modelId
Saves a new document for the currently logged in user.
The results for this call will be the complete, inserted document, including default values for properties that have them defined, the auto generated objectId, createdAt, and modifiedAt values.
The following options are available.
option | description | default |
---|
mapId | The name of the data map that you'd like to use to transform the doc to the format of modelId . The format of the incoming JSON document must match the format expected by the inbound transform script for the given mapId . | none |
var newTask = {
title: 'New task',
priority: 'high'
};
ydClient.api.insert('yodata.task', newTask , function(err, insertedTask) {
if (err) {
} else {
}
});
YDClient.save (modelId, doc, callback)
required scope: PUT:modelId
Updates an existing, complete document for the currently logged in user. You must load the entire document from either a find
, findById
, or findOne
call first, update the poperties you'd like to change, then pass the entire document back to the update
method.
If you are going to use the save
method, you should use documents that have not been populated with related records, or have limited the fields in the response.
Using the save
method will overwrite the entire document with whatever you pass as the doc
parameter.
The results for this call will be the complete, updated document.
previouslyLoadedTask.title = 'New title for existing task';
ydClient.api.save('yodata.task', previouslyLoadedTask , function(err, updatedTask) {
if (err) {
} else {
}
});
YDClient.update(modelId, objectId, modifier, callback)
required scope: PATCH:modelId
Updates part of a document, using the objectId
parameter to indicate which document to update. The modifier
parameter should be an object containing one or more standard update
parameters for a mongodb update
collection method.
For example, if you want to change the firstName
property of a record you would use {$set: { firstName: 'Bob' }}
.
At least one update operator is required, but $isolated
, $bit
and $currentDate
are not supported.
Please see the mongoDB documentation regarding modifying documents for further informaiton.
var modifier = {
$set: {
title: 'Updated Title'
},
$unset: {
notes: ''
}
};
ydClient.api.update('yodata.task', task.objectId, modifier , function(err, updatedTask) {
if (err) {
} else {
}
});
YDClient.remove (modelId, objectId, callback)
required scope: DELETE:modelId
Deletes one or more documents, with the given objectId(s), for the current user. To delete more than one record, you may pass a comma separated list of objectId
s. If no error is returned, the command completed successfully.
ydClient.api.remove('yodata.task', task.objectId, function(err) {
if (err) {
} else {
}
});
var listOfObjectIds = ids.join(',');
ydClient.api.remove('yodata.task', listOfObjectIds, function(err) {
if (err) {
} else {
}
});
YDClient.findOne (modelId, options, callback)
required scope: GET:modelId
Returns exactly one document, with the given criteria, for the current user. The result will be a single object, if found.
The following options are available.
option | description | default |
---|
criteria | Using the mongoDB syntax to perform a find. | none |
fields | A comma separated list of fields to return in the results, like 'firstName,lastName' . Or, to omit a field, prepend a minus sign to the field name, like 'firstName,lastName,-objectId' | none |
populate | An object that specifies the options to include related data from a referenced model. | none |
sort | The sort order for your results. Use the mongoDb syntax for sorting | { createdAt: -1 } |
var options = {
criteria: {
title: 'test',
priority: 'high'
},
sort: {
modifiedAt: -1
},
fields: 'title,priority',
populate: {
path: 'files',
match: {fileExtension: '.jpg'},
select: 'fileName fileSize',
options: {
limit: 5,
sort: {fileSize: -1}
}
}
}
ydClient.api.findOne('yodata.task', options, function(err, task) {
if (err) {
} else {
}
});
YDClient.findById (modelId, objectId, [options], callback)
required scope: GET:modelId
Returns exactly one document, with the given objectId, for the current user. The result will be a single object, if found. An error will be returned if the objectId could not be located for the current user.
The following options are available.
option | description | default |
---|
fields | A comma separated list of fields to return in the results, like 'firstName,lastName' . Or, to omit a field, prepend a minus sign to the field name, like 'firstName,lastName,-objectId' | none |
populate | An object that specifies the options to include related data from a referenced model. | none |
var options = {
fields: 'title,priority',
populate: {
path: 'files',
match: {fileExtension: '.jpg'},
select: 'fileName fileSize',
options: {
limit: 5,
sort: {fileSize: -1}
}
}
}
ydClient.api.findById('yodata.task', objectId, options, function(err, task) {
if (err) {
} else {
}
});
YDClient.find (modelId, options, callback)
required scope: GET:modelId
Returns an array of documents, including metadata for the total number of records that match the given criteria
option, as well as URLs to obtain the first, previous, next, and last page of documents, based on the given offset
and limit
of the current query. The following options are available.
option | description | default |
---|
criteria | Using the mongoDB syntax to perform a find | none |
limit | The maximum number of records to return | 10 |
offset | The number of records to skip. | 0 |
sort | The sort order for your results. Use the mongoDb syntax for sorting | { createdAt: -1 } |
fields | A comma separated list of fields to return in the results, like 'firstName,lastName' . Or, to omit a field, prepend a minus sign to the field name, like 'firstName,lastName,-objectId' | none |
populate | An object that specifies the options to include related data from a referenced model. | none |
Here's an example of how to sort by a lastName field, in reverse alphabetical order, returning the second set of 100 documents.
var options = {
sort: { lastName: -1 },
limit: 100,
skip: 100
}
ydClient.api.find('yodata.task', options, function(err, results) {
if (err) {
} else {
}
});
YDClient.distinct(modelId, options, callback)
required scope: GET:modelId
Returns unique values from a collection, based on the given fields
option. For example, if you use the fields
option with a value of lastName
the result set will be a list of unique last names (in no particular order). Sorting must be performed locally, after the results are returned. If you require a sorted list, please use the aggregate
method and use the $sort
aggregation operator in the last stage.
The following options are available.
option | description | default |
---|
criteria | Using the mongoDB syntax to perform a find. | none |
fields | The path to the single field from which to return the distinct set of values. | none |
populate | An object that specifies the options to include related data from a referenced model. | none |
YDClient.count(modelId, [options], callback)
required scope: GET:modelId
Pass the criteria
option to return the count of records that match the criteria. If no criteria
option is passed, the result will be the total number of documents in the given collection for the current user.
The following options are available.
option | description | default |
---|
criteria | Using the mongoDB syntax to perform a find. | none |
The following query returns the count of tasks that are not completed. The results
return value is an object with one key, count
. For example, if the number of documents found was 10 the response would be { count: 10 }
.
var options = {
criteria: {
completed: false
}
}
ydClientUi.api.count('yodata.task', options, function(err, results) {
if (err) {
} else {
console.log(results.count);
}
});
YDClient.aggregate(modelId, options, callback)
required scope: GET:modelId
Use the pipeline
option to pass an array of mongoDB aggregation stages. The following is an example of how you could query the yodata.tasks
collection to return a sorted list of tags and their count:
var options = {
pipeline: [
{
$unwind: '$tags'
},
{
$group: {
_id: '$tags',
count: {
$sum: 1
}
}
},
{
$sort: {
_id: 1
}
}
]
}
ydClientUi.api.aggregate('yodata.task', options, function(err, tagList) {
if (err) {
} else {
}
});
YDClient.userProfile(callback)
required scope: GET:user-profile
Returns the profile of the user or organization associated with the current authentication token.
YDClient.uploadFile(formData, callback)
required scope: POST:files
Allows you to upload a binary file using a multi-part form data post. The result in the callback function is a special file
object, which you can use to reference the file in a collection.
YDClient.generateDownloadUrlForPrivateFileById(fileId, callback)
required scope: GET:files
Public files have a publicFileUrl
property, which would allow you to access the file directly using an img
tag (if it's an image) or a link. For private files a two step process is used to generate a download token, which can be used to download the file from the download URL. For security reasons the URL that's returned by this function is only valid for 10 minutes.