Stelace Javascript SDK makes it easy to use Stelace API in your client or server-side JavaScript applications.
What is Stelace?
Stelace provides search, inventory and user management infrastructure for Web platforms, ranging from search-intensive marketplaces to online community apps. Stelace offers powerful backend and APIs including advanced search, automation, and content delivery, to let you focus on what makes your platform unique.
- Full Stelace API endpoints coverage
- API key and Auth Tokens handling
- ES6 modules / bundler support
- Chrome
- Firefox
- Edge
- Safari
- IE11 (except when using pre-packaged evergreen version)
- Node.js (>=10.18)
Other browsers with similar feature set should also work.
npm install stelace
# Or
yarn stelace
This package needs to be used with secret or publishable api keys you can find in Stelace Dashboard.
const { createInstance } = require('stelace')
const stelace = createInstance({ apiKey: 'seck_test_...' })
const asset = await stelace.assets.create({
name: 'Car'
})
With callback
const Stelace = require('stelace')
const stelace = Stelace.createInstance({ apiKey: 'seck_test_...' })
stelace.assets.create({
name: 'Car'
}, function (err, asset) {
err // null if no error occurred
asset // the created asset object
})
Warning: secret apiKey
seck_...
must only be used in secure environments as it grants all endpoint permissions.
For browser you can either install (with npm/yarn) or add a <script>
tag in your HTML.
Installing the SDK is the recommended way:
- tree-shaking can reduce Stelace SDK size by 70% with shared dependencies (mostly axios and core-js polyfills).
- no surprise due to potential jsDelivr/unpkg CDN failure.
You just have to use ES modules with your favorite bundler like Webpack:
import { createInstance } from 'stelace'
const stelace = createInstance({ apiKey: 'pubk_test_...' })
//…
Note: please use publishable apiKey
pubk_...
in browser environment.
For convenience you may want to load one of the UMD files we built for you instead:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/stelace.browser.min.js"></script>
You can then use stelace
global variable.
We offer a smaller build for modern browsers (excluding IE11 and Opera Mini in particular):
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/stelace.evergreen.min.js"></script>
Unminified and map files are also available.
A publishable api key identifies your platform and enables all publicly accessible endpoints.
You’ll often need to call endpoints as one of your authenticated platform user
s (typically from your front-end).
Publishable apiKey is also what you need here since each user has its own set of permissions depending on user roles
: all user permissions are automatically added to public permissions.
const { createInstance } = require('stelace')
const stelace = createInstance({ apiKey: 'pubk_test_...' })
// Login as the user '[email protected]'
await stelace.auth.login({
username: '[email protected]',
password: 'secretPassword'
})
// Any actions performed will be associated to this user
await stelace.assets.create(...)
// Logout to destroy the current session
await stelace.auth.logout()
After successful login, the access and refresh tokens will be returned.
Stelace SDK handles the authentication for you and will automatically renew the access token when it's expired.
Custom authentication
Advanced options are available for custom authentication workflows.
By default, Stelace provides a default token store for the authentication tokens storage. Tokens are stored into localStorage in browser environment and into memory in Node.js.
If custom storage is needed, a token store can be provided at initialization:
const myCustomTokenStore = {...}
const stelace = createInstance({ apiKey: 'pubk_test_...', tokenStore: myCustomTokenStore })
or at run-time:
stelace.setTokenStore(myCustomTokenStore)
A token store must be an object implementing the following functions:
- getTokens()
- setTokens(tokens:
Object
) - removeTokens()
For convenience, we provide stelace.getTokenStore()
if you need to perform some operation on tokens.
In some case (e.g. external authentication), you may need a custom workflow to refresh tokens.
beforeRefreshToken
function can also be provided at initialization:
const myBeforeRefreshToken = function (tokens, cb) {
getNewTokens(tokens, function (err, newTokens) {
cb(err, newTokens)
})
}
const stelace = createInstance({ apiKey: 'pubk_test_...', beforeRefreshToken: myBeforeRefreshToken })
or at run-time:
stelace.setBeforeRefreshToken(myBeforeRefreshToken)
The function beforeRefreshToken
can also be a promise:
const myBeforeRefreshToken = async function (tokens) {
const newTokens = await getNewTokens(tokens)
return newTokens
}
Note: Any token will be stored as is in token store.
Each method request returns a promise (or await
as above) that you can use in place of callbacks:
// Create an asset type and create an asset with it
stelace.assetTypes.create({
name: 'Renting',
timeBased: true,
infiniteStock: false
}).then(function (assetType) {
return stelace.assets.create({
name: 'Car',
assetTypeId: assetType.id
})
}).then(function (asset) {
// Created asset
}).catch(function (err) {
// Handle this error
})
Some information about the response is provided in the lastResponse
property as convenience:
asset.lastResponse.requestId
asset.lastResponse.statusCode
When pagination is available in list endpoints, you’ll directly get results
array as response:
const assets = await stelace.assets.list()
console.log(Array.isArray(assets)) // true
console.log(assets.lastResponse.statusCode) // 200
// For API version 2019-05-20 (offset pagination)
console.log(assets.paginationMeta.page) // 1
// For higher API version (cursor pagination)
console.log(assets.paginationMeta.hasNextPage)
Here are the properties included in paginationMeta
:
For API version 2019-05-20 (offset pagination):
assets.paginationMeta.nbResults
assets.paginationMeta.nbPages
assets.paginationMeta.page
assets.paginationMeta.nbResultsPerPage
For higher API version (cursor pagination):
assets.paginationMeta.startCursor
assets.paginationMeta.endCursor
assets.paginationMeta.hasPreviousPage
assets.paginationMeta.hasNextPage
assets.paginationMeta.nbResultsPerPage
Currently, the following list endpoints don't support pagination:
- asset type
- category
- role
- webhook
- workflow
Options are additional parameters that you can pass after the required arguments after any given method.
All methods can accept an optional options
object containing one or more of the following:
stelaceVersion
- use a specific Stelace API version for this requeststelaceUserId
- perform the request as the specified user ID, needs specific permissions to do sostelaceOrganizationId
- perform the request as the specified organization ID, the user must belong to the specified organization;null
value allowed to remove the global value set bystelace.setOrganizationId()
This options
object can be included as the last argument for any method (or second to last when using callbacks):
// Only the category data object
stelace.categories.create({
name: 'Sport'
})
// The category data object and the options object
stelace.categories.create({
name: 'Sport'
}, {
stelaceVersion: '2018-07-30'
})
Request timeout in case of network failure is configurable (the default is 30 seconds):
stelace.setTimeout(10000); // in ms (10 seconds)
The current version of SDK (0.14.0
) is compatible with Stelace API up to version 2019-05-20
.
Run all tests:
yarn
yarn prepare # To install husky hooks
yarn test
Run tests in browser environments (Chrome and Firefox):
yarn test:browser-local
Most of the methods follow the same schema concerning arguments:
Id: string
- Object ID
queryParams: object
- Query parameters in GET requests (usually for pagination)
data: object
- Body of the request for POST/PATCH requests (usually for creation or update of an object)
options: object
- Options parameters described above
callback: function
- Callback function. Omit it when using promises
The optional arguments are within [brackets].
stelace.apiKeys.list([queryParams], [options], [callback])
stelace.apiKeys.read(apiKeyId, [queryParams], [options], [callback])
stelace.apiKeys.create(data, [options], [callback])
stelace.apiKeys.update(apiKeyId, data, [options], [callback])
stelace.apiKeys.remove(apiKeyId, [options], [callback])
stelace.assets.list([queryParams], [options], [callback])
stelace.assets.read(assetId, [queryParams], [options], [callback])
stelace.assets.create(data, [options], [callback])
stelace.assets.update(assetId, data, [options], [callback])
stelace.assets.remove(assetId, [options], [callback])
stelace.assetTypes.list([queryParams], [options], [callback])
stelace.assetTypes.read(assetTypeId, [queryParams], [options], [callback])
stelace.assetTypes.create(data, [options], [callback])
stelace.assetTypes.update(assetTypeId, data, [options], [callback])
stelace.assetTypes.remove(assetTypeId, [options], [callback])
stelace.auth.login(data, [options], [callback])
stelace.auth.info()
Returns an object with the following properties:
- isAuthenticated:
boolean
- userId:
string|null
stelace.auth.logout()
To detect when the user session has expired and handle it properly, you can listen to the following error event:
stelace.onError('userSessionExpired', function () {
// In browser, you can notify users that they must reconnect
// ...
})
If there are any authentication tokens, they will be automatically removed.
To stop listening to the event, you can unsubscribe by calling the returned function:
const unsubscribe = stelace.onError('userSessionExpired', function () { ... })
unsubscribe() // stops listening
stelace.auth.getTokens(data, [options], [callback])
stelace.auth.check(data, [options], [callback])
Following methods are provided to hit custom endpoints with Stelace authentication headers. This is especially useful if you need to call external endpoints with custom logic, e.g. using serverless lambda functions.
url
can be a relative path to Stelace REST API endpoints or an absolute external URL.
Stelace API endpoint (relative) path is equivalent to using the equivalent SDK method, like:
stelace.users.create(data)
// same as
stelace.forward.post('/users', data)
forward.method
s map to corresponding HTTP verbs.
stelace.forward.get(url, [callback])
stelace.forward.post(url, [data], [callback])
stelace.forward.put(url, [data], [callback])
stelace.forward.patch(url, [data], [callback])
stelace.forward.del(url, [callback])
stelace.forward.options(url, [callback])
stelace.availabilities.getGraph([queryParams], [options], [callback])
stelace.availabilities.list([queryParams], [options], [callback])
stelace.availabilities.create(data, [options], [callback])
stelace.availabilities.update(availabilityId, data, [options], [callback])
stelace.availabilities.remove(availabilityId, [options], [callback])
stelace.categories.list([queryParams], [options], [callback])
stelace.categories.read(categoryId, [queryParams], [options], [callback])
stelace.categories.create(data, [options], [callback])
stelace.categories.update(categoryId, data, [options], [callback])
stelace.categories.remove(categoryId, [options], [callback])
stelace.config.read([options], [callback])
stelace.config.update([data], [options], [callback])
stelace.config.readPrivate([options], [callback])
stelace.config.updatePrivate([data], [options], [callback])
stelace.customAttributes.list([queryParams], [options], [callback])
stelace.customAttributes.read(customAttributeId, [queryParams], [options], [callback])
stelace.customAttributes.create(data, [options], [callback])
stelace.customAttributes.update(customAttributeId, data, [options], [callback])
stelace.customAttributes.remove(customAttributeId, [options], [callback])
stelace.documents.getStats([queryParams], [options], [callback])
stelace.documents.list([queryParams], [options], [callback])
stelace.documents.read(documentId, [queryParams], [options], [callback])
stelace.documents.create(data, [options], [callback])
stelace.documents.update(documentId, data, [options], [callback])
stelace.documents.remove(documentId, [options], [callback])
stelace.entries.list([queryParams], [options], [callback])
stelace.entries.read(entryId, [queryParams], [options], [callback])
stelace.entries.create(data, [options], [callback])
stelace.entries.update(entryId, data, [options], [callback])
stelace.entries.remove(entryId, [options], [callback])
stelace.events.getStats([queryParams], [options], [callback])
stelace.events.list([queryParams], [options], [callback])
stelace.events.read(eventId, [queryParams], [options], [callback])
stelace.events.create(data, [options], [callback])
stelace.messages.list([queryParams], [options], [callback])
stelace.messages.read(messageId, [queryParams], [options], [callback])
stelace.messages.create(data, [options], [callback])
stelace.messages.update(messageId, data, [options], [callback])
stelace.messages.remove(messageId, [options], [callback])
stelace.orders.list([queryParams], [options], [callback])
stelace.orders.read(orderId, [queryParams], [options], [callback])
stelace.orders.preview(data, [options], [callback])
stelace.orders.create(data, [options], [callback])
stelace.orders.update(orderId, data, [options], [callback])
stelace.orderLines.read(orderLineId, [queryParams], [options], [callback])
stelace.orderLines.create(data, [options], [callback])
stelace.orderLines.update(orderLineId, data, [options], [callback])
stelace.orderMoves.read(orderMoveId, [queryParams], [options], [callback])
stelace.orderMoves.create(data, [options], [callback])
stelace.orderMoves.update(orderMoveId, data, [options], [callback])
stelace.password.change(data, [options], [callback])
stelace.password.resetRequest(data, [options], [callback])
stelace.password.resetConfirm(data, [options], [callback])
stelace.permissions.check(data, [options], [callback])
stelace.ratings.getStats([queryParams], [options], [callback])
stelace.ratings.list([queryParams], [options], [callback])
stelace.ratings.read(ratingId, [queryParams], [options], [callback])
stelace.ratings.create(data, [options], [callback])
stelace.ratings.update(ratingId, data, [options], [callback])
stelace.ratings.remove(ratingId, [options], [callback])
stelace.roles.list([queryParams], [options], [callback])
stelace.roles.read(roleId, [queryParams], [options], [callback])
stelace.roles.create(data, [options], [callback])
stelace.roles.update(roleId, data, [options], [callback])
stelace.roles.remove(roleId, [options], [callback])
stelace.savedSearch.list([queryParams], [options], [callback])
stelace.savedSearch.read(savedSearchId, [queryParams], [options], [callback])
stelace.savedSearch.create(data, [options], [callback])
data
is the object that is passed to POST /search
endpoint (same endpoint as stelace.search.results
method), but with two differences:
stelace.savedSearch.create
method automatically setssave
totrue
- the property
name
is required to create a saved search
stelace.savedSearch.update(savedSearchId, data, [options], [callback])
stelace.savedSearch.remove(savedSearchId, [options], [callback])
stelace.search.results(data, [options], [callback])
Deprecated version: stelace.search.list(data, [options], [callback])
stelace.tokens.checkRequest(data, [options], [callback])
stelace.tokens.checkConfirm(tokenId, [queryParams], [options], [callback])
stelace.transactions.list([queryParams], [options], [callback])
stelace.transactions.read(transactionId, [queryParams], [options], [callback])
stelace.transactions.preview(data, [options], [callback])
stelace.transactions.create(data, [options], [callback])
stelace.transactions.update(transactionId, data, [options], [callback])
stelace.transactions.createTransition(transactionId, data, [options], [callback])
stelace.users.checkAvailability(queryParams, [options], [callback])
stelace.users.list([queryParams], [options], [callback])
stelace.users.read(userId, [queryParams], [options], [callback])
stelace.users.create(data, [options], [callback])
stelace.users.update(userId, data, [options], [callback])
stelace.users.remove(userId, [options], [callback])
stelace.users.joinOrganizationOrUpdateRights(userId, organizationId, data, [options], [callback])
stelace.users.removeFromOrganization(userId, organizationId, [options], [callback])
stelace.webhooks.list([queryParams], [options], [callback])
stelace.webhooks.read(webhookId, [queryParams], [options], [callback])
stelace.webhooks.create(data, [options], [callback])
stelace.webhooks.update(webhookId, data, [options], [callback])
stelace.webhooks.remove(webhookId, [options], [callback])
stelace.workflows.list([queryParams], [options], [callback])
stelace.workflows.read(workflowId, [queryParams], [options], [callback])
stelace.workflows.create(data, [options], [callback])
stelace.workflows.update(workflowId, data, [options], [callback])
stelace.workflows.remove(workflowId, [options], [callback])