ec.datamanager.js
DEPRECATED: This module is deprecated in favor of ec.sdk.
JavaScript SDK for ec.datamanager. By entrecode.
Simply use the generated APIs of the ec.datamanager with JavaScript. Supports usage in frontend (web) and backend (Node.js).
The SDK is fully promise-based. Since version 0.6.0
the SDK is fully HAL based and uses traverson, traverson-hal, and halfred.
Contents
Installation
With npm (for backend or frontend usage):
npm install ec.datamanager
Usage
Loading the module in node.js:
var DataManager = ;// or;;
Loading the minified module in the Browser:
<script src="bower_components/ec.datamanager.js/build/datamanager.min.js"></script>
DataManager
is then globally available.
(if you did not install using bower, the first part of the path may be different)
Initialization
You need to connect to your Data Manager API using the DataManager(options)
constructor.
Initializing dataManager with existing token:
var dataManager = url: 'https://datamanager.entrecode.de/api/abcdef' accessToken: '8c3b7b55-531f-4a03-b584-09fdef59cb0c';
Initialization without token:
var dataManager = url: 'https://datamanager.entrecode.de/api/abcdef';
Alternative:
var dataManager = id: 'abcdef12';
Initialization with clientID
for user management:
var dataManager = id: 'beefbeef' clientID: 'myAwesomeClient';
Initialization with errorHandler
:
var dataManager = id: 'beefbeef' { console; };
DataManager
Resolve
Retrieves information about the connected Data Manager. Like title, id, …
dataManager;
Permission Check
To check if the currently instantiated Data Manager has a specific right you can use can(…)
.
dataManager; dataManager;
Enable Cache
dataManager…// ORdataManager// ORdataManager;
If you use caching, you should not have the fields $loki
and meta
in your Model.
Clear Cache
dataManager… // only myModel gets cleared// ORdataManager
Model
Model List
Retrieves all models of a Data Manager:
dataManager;
Model Resolve
When creating a model directly it will not have the metadata ready. You can retrieve the metadata with resolve()
.
dataManager;
Model enable cache
dataManager;
Model clear cache
dataManager;
Get JSON Schema
JSON schemas exist for models. To get one call getSchema()
.
dataManager // will load 'GET' schema; // For PUT or POST schema:dataManager;
Entries
Get EntryList
size: 0
will return ALL entries
dataManager
Get EntryList with cacheType
also works on entry(…)
and entries(…)
dataManager;…dataManager;…dataManager;…// the following type only works on entryList, is handled like default on entry/entriesdataManager;
Get Entries
size: 0
will return ALL entries
dataManager;
Get Entry
dataManager; // OR for nested entries dataManager // since 0.6.0 no longer object;
Get nested Entry
Just like get entry but nested entries will be resolved as proper datamanager SDK objects.
dataManager // since 0.6.0 no longer object;
Create Entry
dataManager;
Delete Entry
The delete()
function is an instance method of Entry
. Just return entry.delete()
in your entry promise handler:
dataManager;
Update Entry
Works similar to delete()
:
dataManager;
Get Title of Entry
Returns the title of any nested entry in the entry.
Example:
dataManager;
Get Model Name of Entry
Returns the model title of any nested entry in the entry.
Example:
dataManager;
Users in the SDK
Register Anonymous User.
// register anonymous user.dataManager;
The accessToken
is a property of the DataManager instance:
dataManageraccessToken; // the currently used token for user authentication
Logout aka. clear accessToken and reset sdk.
…// dataManager has a accessToken.dataManager;// accessToken has been cleared and internal API connection was reset.…
Email Available
You can check for email availability before you regiser a user:
dataManager;
Get Authorizaton Links
In order to receive prefilled urls for all other account management relations you can use getAuthLink()
.
dataManager;
This function provides you with all links found in the root API response with the relation <dataManagerShortID>:_auth/<linkName>
. Most of them require clientID
either set in the DataManager instance or directly as shown above. Others require additional properties (e.g. password-reset
: requires clientID
and email
).
Applicable link names are:
anonymous
signup
login
password-reset
email-available
public-key.pem
Additional documentation for user management in Data Manager APIs can be found in the Data Manager documentation itself.
Get Account
Get information about the logged in account.
dataManager;
Asset File Helper
The SDK can help you getting asset files, and image assets in the right sizes. All file Helper can receive a locale
property as last parameter if you want to request a specific locale (not the choosen one from Data Manager).
Note On Static Helper
The following functions are also provided as static functions in DataManager
. E.g. you can call DataManager.getFileUrl(assetID).then(…);
without connecting to a DataManager. This only works for assets in https://datamanager.entrecode.de
DataManagers (not in Staging).
File Helper
dataManager
Image Helper
dataManager
getImageURL
expects a pixel value. The largest edge of the returned image will be at least this value pixels in size, if available.
Thumbnail Helper
dataManager
The returned image will be a square-cropped variant with (in this example) at least 100 pixels (pixel value can be set as with getImageURL
). Available sizes are 50, 100, 200 and 400 px. Other values will be mapped to next bigger one.
Assets
Get AssetList
dataManager;
Get Assets
dataManager;
Get Asset
dataManager;
Create Asset(s)
dataManager;
For node.js acceptable inputs are:
- A path string to a local file (
path/to/file
) - An array of path strings (
['path/to/file1', 'path/to/file2']
)
For browsers acceptable inputs are:
-
Example:
;
Edit Asset
dataManager;
Delete Asset
dataManager;
Asset File Helper
var url = asset; // original file
Asset Image Helper
var url = asset // size 500 image files
getImageUrl
expects a pixel value. The largest edge of the returned image will be at least this value pixels in size, if available.
Asset Thumbnail Helper
var url = asset; // size 100 thumb files
The returned image will be a square-cropped variant with (in this example) at least 100 pixels (pixel value can be set as with getImageUrl
). Available sizes are 50, 100, 200 and 400 px. Other values will be mapped to next bigger one.
Asset getOriginal Helper
var file = asset;console; // the file urlconsole; // the resolution { width, heigth }
Tags
Get TagList
dataManager;
Get Tags
dataManagertags;
Get Tag
dataManager;
Edit Tag
dataManager;
Delete Tag
dataManager;
Errors
ec_sdk_no_url_or_id_set
You did not specify a id or url in DataManager constructor.ec_sdk_invalid_url
The url (or url generated from id) was malformed.ec_sdk_model_not_found
When you tried tomodel(…).resolve()
a model which is not available in the Data Manager.ec_sdk_invalid_method_for_schema
You specified the wrong method formodel(…).getSchema(<method>)
. Onlyget
,put
, andpost
are allowed.ec_sdk_not_logged_in
Your tried to resolve the account info without being logged in.
Documentation
class DataManager
Constructor
new DataManager(options)
returns new DataManager Object
options
contains following keys: url
, accessToken
,id
, errorHandler
and clientID
. All are optional, but either url
or id
have to be set. Depending on the Data Manager Settings you will not be able to modify entries etc. when no accessToken is spcified.
Examples:
// initializing dataManager with existing tokenvar dataManager = url: 'https://datamanager.entrecode.de/api/abcdef' accessToken: '8c3b7b55-531f-4a03-b584-09fdef59cb0c'; // Initialization without tokenvar dataManager = url: 'https://datamanager.entrecode.de/api/abcdef' { ; }; // Alternativevar dataManager = id: 'abcdef' clientID: 'myAwesomeClientID';
DataManager Static Methods
getFileURL(assetID, [locale])
returns a file url. Optionally, a specific locale
can be requested.
The promise is getting rejected if no file is found.
getImageURL(assetID, [size, locale])
returns an image file. size
is optional and states the size in pixels the largest edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. If size
is omitted, the largest size (i.e. the original image) is returned. Optionally, a specific locale
can be requested. The promise is getting rejected if no file is found. The following sizes are being returned: 256, 512, 1024, 2048, 4096.
Example: The source image has a largest edge of 3000 pixels. getImageURL(id, 1000)
will return the 1024px version. getImageURL(id, 4096)
will return the original file with 3000 pixels.
getImageThumbURL(assetID, size[, locale])
returns an image thumbnail (square cropped). size
is required and states the size in pixels the thumbnail square edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. Optionally, a specific locale
can be requested. The promise is getting rejected if no file is found. The following sizes are being returned: 50, 100, 200, 400
cloneEntries(entries)
, cloneAssets(assets)
, cloneTags(tags)
returns a cloned copy of entries
, assets
, or tags
.
cloneEntry(entry)
deprecated, cloneAsset(asset)
, cloneTag(tag)
returns a cloned copy of the entrie
, asset
, or tag
.
DataManager Instance Methods
enableCache(stringOrArrayofObject[, lokiJsEnv[, maxCacheAge]])
enables caching for the given models. Either one model title (String
) or multiple model titles (Array
) or multiple model titles(key
) with custom maxCacheAge(value
) (Object
). returns a Promise which resolves to a array of LokiJS collections.
If you use caching, you should not have the fields '$loki' and 'meta' in your Model.
clearCache(stringOrArray)
disables and cleares the cache for the given models. Either one model title (String
) or multiple model titles (Array
).
return a Promise which resovles after successfully clearing cache.
asset(identifier)
returns an Asset object as Promise. identifier
(String) is required.
model(identifier)
returns a Model object. identifier
(String) is required.
modelList()
returns available Models as Promise.
assets()
returns available Assets as Promise.
assetList()
returns available Assets as Promise. Promise will resolve a list object containing the properties assets
, count
, and total
.
createAsset(formData|filePath|arrayOfFilePaths, tags, title)
creates a new Asset. Returns an Array of Promsises to retrieve the created Assets.
getFileURL(assetID, [locale])
returns a file url. Optionally, a specific locale
can be requested.
The promise is getting rejected if no file is found.
getImageURL(assetID, [size, locale])
returns an image file. size
is optional and states the size in pixels the largest edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. If size
is omitted, the largest size (i.e. the original image) is returned. Optionally, a specific locale
can be requested. The promise is getting rejected if no file is found. The following sizes are being returned: 256, 512, 1024, 2048, 4096.
Example: The source image has a largest edge of 3000 pixels. getImageURL(id, 1000)
will return the 1024px version. getImageURL(id, 4096)
will return the original file with 3000 pixels.
getImageThumbURL(assetID, size[, locale])
returns an image thumbnail (square cropped). size
is required and states the size in pixels the thumbnail square edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. Optionally, a specific locale
can be requested. The promise is getting rejected if no file is found. The following sizes are being returned: 50, 100, 200, 400
registerAnonymous()
For creating a new anonymous user account. Returns user object with jwt token and accountID. The token is also assigned to DataManager and used with subsequent requests.
Example:
dataManager;
logout()
Syncronous method for clearing the accessToken
of the SDK and resetting the internal API connection.
getAuthLink(linkName)
returns an auth link as Promise.
Please see user guide above for details.
emailAvailable(email)
return an email availability check as Promise.
can(permission)
Checks if the currently connected Data Manager is able to perform permission
. Permission format is something like <model>:<method>:<field>
. Additional documentation can be found in generated documentation of the Data Manager.
DataManager Instance Properties
accessToken
Access Token for user, ornull
/undefined
if not set.id
ShortID of the connected Data Manager.url
The url of the connected Data Manager.clientID
ClientID which will be used to generate authLinks, ornull
/undefined
if not set.errorHandler
The global errorHandler for all erorrs which can occur.DB_NODEJS
LokiJS env for node.DB_CORDOVA
LokiJS env for cordova.DB_BROWSER
LokiJS env for browsers.
Model object
Connecting a Model
var myModel = dataManager;
returns Model Object which is a promise.
Model Instance Methods
enableCache([lokiJsEnv [, maxCacheAge])
enables caching for the connected model with maxCacheAge
(in ms). Returns a Promise which resolves to a LokiJS collection.
clearCache()
disables and cleares the cache for the model. return a Promise which resovles after successfully clearing cache.
entries(options)
/entryList(options)
returns JSON Array of Entries (async).
The request can be configured using options
.
Valid keys are:
size
– number of entries to get (default: 10)page
– which page of entries to get when there are more thansize
(default: 1)sort
– sort by a different than the default property. Syntax:{direction}{property}[,…]
wheredirection
defaults to+
(ascending order) and can be set to-
(descending order) andproperty
is the property to sort after. Can even be multiple properties (Array).fields
- Array of field names to include in the response (Will not work with cached data).filter
– for filtering after properties. Always an object with properties as key. The keys can have the following possible values:exact
: exact filter. Value is the value to match exactlysearch
: search filter. Value is the value to includefrom
: Range filter: value is the value to have as lower end (≥)to
: Range filter: value is the value to have as upper end (≤)any
: Multiple-exact-match filter. Value is an Array containing allowed values (OR)all
: Multiple-exact-match filter. Value is an Array containing required values (AND)
cacheType
- selected cachedType (default:default
)default
- refreshes data when stale, cached otherwiserefresh
- refreshes data every timestale
- resolves promise directly with stale data. addrefreshedData
(Promise
) to result which can be used to refresh the data asyncronously. This only works onentryList
.
Example:
// get entriesdataManager
entries()
will return an array of entries. entryList()
will return an object with the following structure:
entries: /* array of entries */ total: 10 count: 5 next: /* Promise Factory */ prev: /* Promise Factory */ first: /* Promise Factory */
entry(id [, levels, fields])
returns a Entry object as Promise. Levels property can be used to request nested entries. Fields may be used to only get selected fields in the response (Will not work with cached data).
nestedEntry(id [, levels, fields])
returns a Entry object as Promise. Levels property can be used to request nested entries. Fields may be used to only get selected fields in the response (Will not work with cached data). Resolved nested elementes are proper SDK objects with all functions like save()
and delete()
.
createEntry(object)
create a new entry. Returns the Entry.
deleteEntry(id)
return a Promise for deleting an entry.
getSchema([method])
retrieve JSON Schema. method
is get
by default. Other possible values: put
, post
.
resolve()
return a resolved model as Promise.
Can be used when creating a model object without calling modelList()
to resolve model metadata.
Model Instance Properties
id
The model idtitle
The model title. Same asid
.metadata
ContainstitleField
and other model metadata.
Entry Object
Entry properties
values
The properties of the Entry are available atentry.values
.
Entry Instance Methods
save()
saves the entry. Promise.
Example:
// update entrydataManager
delete()
deletes the entry. Promise.
Example:
// update entrydataManager;
getTitle(String)
gets the title of any child entry identified by String
. Will return String
for single types and Array<String>
for multiple types.
Example:
dataManager;
getModelTitle(String)
gets the model title of any child entry identified by String
.
Example:
dataManager;
clone()
clones an entry.
Example:
dataManager;
getFileUrl(field, locale)
syncronously returns a file url. Optionally, a specific locale
can be requested.
getImageUrl(field, size, locale)
syncronously returns an image file. size
is optional and states the size in pixels the largest edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. If size
is omitted, the largest size (i.e. the original image) is returned. Optionally, a specific locale
can be requested. The following sizes are being returned: 256, 512, 1024, 2048, 4096.
Example: The source image has a largest edge of 3000 pixels. getImageURL(id, 1000)
will return the 1024px version. getImageURL(id, 4096)
will return the original file with 3000 pixels.
getImageThumbUrl(field, size, locale)
syncronously returns an image thumbnail (square cropped). size
is required and states the size in pixels the thumbnail square edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. Optionally, a specific locale
can be requested. The following sizes are being returned: 50, 100, 200, 400
getOriginal(field)
syncronously returns the file object of the original file. Returns undefined on non image assets.
Asset object
Connecting an Asset
var myAsset = dataManager;
returns Asset as a Promise.
Asset properties
value
The properties of the Asset are available atasset.value
.
Asset Instance Methods
save()
saves a changed Asset. Promise.
Example:
dataManager
delete()
deletes the asset. Promise.
Example:
dataManager;
getFileUrl
syncronously returns a file url. Optionally, a specific locale
can be requested.
getImageUrl
syncronously returns an image file. size
is optional and states the size in pixels the largest edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. If size
is omitted, the largest size (i.e. the original image) is returned. Optionally, a specific locale
can be requested. The following sizes are being returned: 256, 512, 1024, 2048, 4096.
Example: The source image has a largest edge of 3000 pixels. getImageURL(id, 1000)
will return the 1024px version. getImageURL(id, 4096)
will return the original file with 3000 pixels.
getImageThumbUrl
syncronously returns an image thumbnail (square cropped). size
is required and states the size in pixels the thumbnail square edge should have at least.
Note that the image may still be smaller if the original image is smaller than size
. Optionally, a specific locale
can be requested. The following sizes are being returned: 50, 100, 200, 400
getOriginal
syncronously returns the file object of the original file. Returns undefined on non image assets.
Tag Object
Connecting a Tag
var myTag = dataManager;
returns Tag as a Promise.
Tag Properties
value
The properties of the Tag are available attag.value
. Typicallytag
andcount
.
Tag Instance Methods
save()
saves a changed Tag. Promise
dataManager;
delete()
deletes the Tag. Promise.
Example:
dataManager;
Tests and Coverage
Before running tests, you need to npm install
the dev dependency modules. For frontend tests phantomjs 2.0
has to be installed globally.
Running backend Tests with mocha (called with npm):
npm test
Alternative, using grunt:
grunt test # tests backend and frontend grunt test-backend # only backend grunt test-frontend # only frontent
Running backend tests with coverage:
grunt coverage
Running frontend Tests with karma:
grunt test-frontend
The task will run a mocked server at port 54815. Make sure it is available.
Installing phantomjs 2.0 with homebrew
brew install phantomjs
Build
Should not be necessary. A new build for frontend usage (minified) can be triggered with
grunt build
(npm install
is needed before for installing dev dependency modules)