Skip to content

rokka-io/rokka.js

Repository files navigation

rokka.js NPM version Build Status Coverage

JavaScript client library for rokka.

rokka.js runs on node as well as within the supported browsers.

Install

npm install rokka

Usage

Using the Rokka class (recommended)

import { Rokka } from 'rokka'

const rokka = new Rokka({
  apiKey: 'apikey',                  // required for most operations
  apiHost: 'https://api.rokka.io',   // default: https://api.rokka.io
  apiVersion: 1,                     // default: 1
  renderHost: 'https://{organization}.rokka.io', // default: https://{organization}.rokka.io
  debug: false,                      // default: false
  transport: {
    requestTimeout: 30000,     // milliseconds to wait for rokka server response (default: 30000)
    retries: 10,               // number of retries when API response is 429 (default: 10)
    minTimeout: 1000,          // minimum milliseconds between retries (default: 1000)
    maxTimeout: 10000,         // maximum milliseconds between retries (default: 10000)
    randomize: true,           // randomize time between retries (default: true)
  }
})

const result = await rokka.sourceimages.list('myorg')
console.log(result)

Using the factory function (backwards compatible)

const rokka = require('rokka')({
  apiKey: 'apikey'
})

const result = await rokka.sourceimages.list('myorg')
console.log(result)

Using in a browser via script tag (UMD)

<script src="https://unpkg.com/rokka"></script>
<script>
  // Factory style
  const client = rokka({ apiKey: 'apikey' })

  // Class style
  const client2 = new rokka.Rokka({ apiKey: 'apikey' })
</script>

Using a proxy

import { HttpsProxyAgent } from 'https-proxy-agent'
import { Rokka } from 'rokka'

const rokka = new Rokka({
  apiKey: 'apikey',
  transport: { agent: new HttpsProxyAgent(proxy) }
})

Documentation

See full API documentation for detailed reference.

Initialization

Creates the internal state object for the Rokka client.

import { Rokka } from 'rokka'
const rokka = new Rokka({ apiKey: 'apikey' })
const rokka = require('rokka')({ apiKey: 'apikey' })

Users

rokka.users.create(email, [organization=null])Promise<RokkaResponse>

Register a new user for the rokka service.

const result = await rokka.users.create('user@example.org')

rokka.users.getId()Promise<string>

Get user_id for current user

const result = await rokka.users.getId()

User

rokka.user.getId()Promise<string>

Get user_id for current user

const result = await rokka.users.getId()

rokka.user.get()Promise<UserResponse>

Get user object for current user

const result = await rokka.user.get()

rokka.user.listApiKeys()Promise<UserApiKeyListResponse>

List Api Keys of the current user

const result = await rokka.user.listApiKeys()

rokka.user.addApiKey([comment=null])Promise<UserApiKeyResponse>

Add Api Key to the current user

const result = await rokka.user.addApiKey('some comment')

rokka.user.deleteApiKey(id)Promise<RokkaResponse>

Delete Api Key from the current user

await rokka.user.deleteApiKey(id)

rokka.user.getCurrentApiKey()Promise<UserApiKeyResponse>

Get currently used Api Key

const result = await rokka.user.getCurrentApiKey()

rokka.user.getNewToken([apiKey], [queryParams={}])Promise<UserKeyTokenResponse>

Gets a new JWT token from the API.

You either provide an API Key or there's a valid JWT token registered to get a new JWT token.

const result = await rokka.user.getNewToken(apiKey, {expires_in: 48 * 3600, renewable: true})

rokka.user.getToken()ApiToken

Gets the currently registered JWT Token from the apiTokenGetCallback config function or null

rokka.user.setToken(token)Promise

Sets a new JWT token with the apiTokenSetCallback function

rokka.user.isTokenExpiring([withinNextSeconds=3600])boolean

Check if the registered JWT token is expiring within these amount of seconds (default: 3600)

rokka.user.getTokenIsValidFor()number

How long a token is still valid for (just checking for expiration time)

Billing

rokka.billing.get(organization, [from], [to])Promise<RokkaResponse>

Retrieve statistics about the billing of an organization

If from and to are not specified, the API will return data for the last 30 days.

const result = await rokka.billing.get('myorg', '2017-01-01', '2017-01-31')

Organizations

rokka.organizations.get(name)Promise<RokkaResponse>

Get a list of organizations.

const result = await rokka.organizations.get('myorg')

rokka.organizations.create(name, billingEmail, displayName)Promise<RokkaResponse>

Create an organization.

const result = await rokka.organizations.create('myorg', 'billing@example.org', 'Organization Inc.')

rokka.organizations.setOption(organizationName, name, value)Promise<RokkaResponse>

Set a single organization option.

rokka.organizations.setOptions(organizationName, options)Promise<RokkaResponse>

Update multiple organization options at once.

const result = await rokka.organizations.setOptions('myorg', {
  protect_dynamic_stack: true,
  remote_basepath: 'https://example.com'
})

Memberships

Roles

  • rokka.memberships.ROLES.READ - read-only access
  • rokka.memberships.ROLES.WRITE - read-write access
  • rokka.memberships.ROLES.UPLOAD - upload-only access
  • rokka.memberships.ROLES.ADMIN - administrative access

rokka.memberships.create(organization, userId, roles, [comment])Promise<RokkaResponse>

Add a member to an organization.

const result = await rokka.memberships.create('myorg', '613547f8-e26d-48f6-8a6a-552c18b1a290', [rokka.memberships.ROLES.WRITE], "An optional comment")

rokka.memberships.delete(organization, userId)Promise<RokkaResponse>

Delete a member in an organization.

await rokka.memberships.delete('myorg', '613547f8-e26d-48f6-8a6a-552c18b1a290')

rokka.memberships.createWithNewUser(organization, roles, [comment])Promise<RokkaResponse>

Create a user and membership associated to this organization.

const result = await rokka.memberships.createWithNewUser('myorg', [rokka.memberships.ROLES.READ], "New user for something")

rokka.memberships.list(organization)Promise<RokkaResponse>

Lists members in an organization.

const result = await rokka.memberships.list('myorg')

rokka.memberships.get(organization, userId)Promise<RokkaResponse>

Get info of a member in an organization.

const result = await rokka.memberships.get('myorg', userId)

Sourceimages

rokka.sourceimages.list(organization, [params={}])Promise<SourceimagesListResponse>

Get a list of source images.

By default, listing sourceimages sorts them by created date descending.

Searching for images can be achieved using the search parameter. Supported are predefined fields like height, name etc. but also user metadata. If you search for user metadata, the field name has to be prefixed with user:TYPE. All fields are combined with an AND. OR/NOT is not possible.

The search also supports range and wildcard queries. Check out the rokka documentation for more.

Sorting works with user metadata as well and can be passed as either an array or as a comma separated string.

const result = await rokka.sourceimages.list('myorg')

Searching for images

const search = {
  'user:int:id': '42',
  'height': '64'
}
const result = await rokka.sourceimages.list('myorg', { search: search })

rokka.sourceimages.downloadList(organization, [params={}])Promise<RokkaDownloadResponse>

Get a list of source images as zip. Same parameters as the list method

const search = {
  'user:int:id': '42',
  'height': '64'
}
const result = await rokka.sourceimages.downloadList('myorg', { search: search })

rokka.sourceimages.get(organization, hash, [queryParams={}])Promise<RokkaResponse>

Get information of a source image by hash.

const result = await rokka.sourceimages.get('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.getWithBinaryHash(organization, binaryHash)Promise<RokkaResponse>

Get information of a source image by its binary hash.

const result = await rokka.sourceimages.getWithBinaryHash('myorg', 'b23e17047329b417d3902dc1a5a7e158a3ee822a')

rokka.sourceimages.download(organization, hash)Promise<RokkaDownloadResponse>

Download image by hash, returns a Stream

const result = await rokka.sourceimages.download('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.downloadAsBuffer(organization, hash)Promise<RokkaDownloadAsBufferResponse>

Download image by hash, returns a Buffer

const result = await rokka.sourceimages.downloadAsBuffer('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.autolabel(organization, hash)Promise<RokkaResponse>

Autolabels an image.

You need to be a paying customer to be able to use this.

const result = await rokka.sourceimages.autolabel('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.autodescription(organization, hash, languages, [force=false])Promise<RokkaResponse>

Autodescribes an image. Can be used for alt attributes in img tags.

You need to be a paying customer to be able to use this.

const result = await rokka.sourceimages.autodescription('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', ['en', 'de'], false)

rokka.sourceimages.create(organization, fileName, binaryData, [metadata=null], [options={}])Promise<RokkaResponse>

Upload an image.

const file = require('fs').createReadStream('picture.png')
const result = await rokka.sourceimages.create('myorg', 'picture.png', file)

With directly adding metadata:

rokka.sourceimages.create('myorg', 'picture.png', file, {'meta_user': {'foo': 'bar'}})

rokka.sourceimages.createByUrl(organization, url, [metadata=null], [options={}])Promise<RokkaResponse>

Upload an image by url.

const result = await rokka.sourceimages.createByUrl('myorg', 'https://rokka.rokka.io/dynamic/f4d3f334ba90d2b4b00e82953fe0bf93e7ad9912.png')

With directly adding metadata:

rokka.sourceimages.createByUrl('myorg', 'https://rokka.rokka.io/dynamic/f4d3f334ba90d2b4b00e82953fe0bf93e7ad9912.png', {'meta_user': {'foo': 'bar'}})

rokka.sourceimages.delete(organization, hash)Promise<RokkaResponse>

Delete image by hash.

await rokka.sourceimages.delete('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.deleteWithBinaryHash(organization, binaryHash)Promise<RokkaResponse>

Delete source images by its binary hash.

await rokka.sourceimages.deleteWithBinaryHash('myorg', 'b23e17047329b417d3902dc1a5a7e158a3ee822a')

rokka.sourceimages.restore(organization, hash)Promise<RokkaResponse>

Restore image by hash.

await rokka.sourceimages.restore('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.copy(organization, hash, destinationOrganization, [overwrite=true])Promise<RokkaResponse>

Copy image by hash to another organization.

await rokka.sourceimages.copy('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', 'anotherorg', true)

rokka.sourceimages.copyAll(organization, hashes, destinationOrganization, [overwrite=true])Promise<RokkaResponse>

Copy multiple images to another organization.

await rokka.sourceimages.copyAll('myorg', ['hash1', 'hash2'], 'anotherorg', true)

rokka.sourceimages.invalidateCache(organization, hash)Promise<RokkaResponse>

Invalidate the CDN cache for a source image.

See the caching documentation for more information.

await rokka.sourceimages.invalidateCache('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.setProtected(organization, hash, isProtected, [options={}])Promise<RokkaResponse>

Set the protected status of a source image.

Important! Returns a different hash, if the protected status changes

const result = await rokka.sourceimages.setProtected('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', true, {
  deletePrevious: false
})

rokka.sourceimages.setLocked(organization, hash, isLocked)Promise<RokkaResponse>

Set the locked status of a source image. Locked images cannot be deleted.

const result = await rokka.sourceimages.setLocked('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', true)

Dynamic metadata

See the dynamic metadata documentation for more information.

rokka.sourceimages.setSubjectArea(organization, hash, coords, [options={}])Promise<RokkaResponse>

Set the subject area of a source image.

The subject area of an image is used when applying the crop operation with the auto anchor to center the cropping box around the subject area.

const result = await rokka.sourceimages.setSubjectArea('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', {
  x: 100,
  y: 100,
  width: 50,
  height: 50
}, {
  deletePrevious: false
})

rokka.sourceimages.removeSubjectArea(organization, hash, [options={}])Promise<RokkaResponse>

Removes the subject area from a source image.

await rokka.sourceimages.removeSubjectArea('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.addDynamicMetaData(organization, hash, name, data, [options={}])Promise<RokkaResponse>

Add/set dynamic metadata to an image

See the dynamic metadata chapter for details.

const result = await rokka.sourceimages.addDynamicMetaData('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', 'crop_area', {
  x: 100,
  y: 100,
  width: 50,
  height: 50
}, {
  deletePrevious: false
})

rokka.sourceimages.deleteDynamicMetaData(organization, hash, name, [options={}])Promise<RokkaResponse>

Delete dynamic metadata of an image

See the dynamic metadata chapter for details.

await rokka.sourceimages.deleteDynamicMetaData('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', 'crop_area', {
  deletePrevious: false
})

rokka.sourceimages.putName(organization, hash, name)Promise<RokkaResponse>

Change the name of a source image.

const result = await rokka.sourceimages.putName('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', name)

Sourceimages meta

User metadata

See the user metadata documentation for more information.

rokka.sourceimages.meta.get(organization, hash)Promise<RokkaResponse>

Get all user metadata for a source image.

See the user metadata documentation for an explanation.

const result = await rokka.sourceimages.meta.get('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

rokka.sourceimages.meta.set(organization, hash, field, value)Promise<RokkaResponse>

Set a single user metadata field on a source image.

See the user metadata documentation for an explanation.

await rokka.sourceimages.meta.set('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', 'somefield', 'somevalue')

rokka.sourceimages.meta.add(organization, hash, data)Promise<RokkaResponse>

Add user metadata to a source image.

See the user metadata documentation for an explanation.

const result = await rokka.sourceimages.meta.add('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', {
  somefield: 'somevalue',
  'int:some_number': 0,
  'delete_this': null
})

rokka.sourceimages.meta.replace(organization, hash, data)Promise<RokkaResponse>

Replace user metadata of a source image with the passed data.

See the user metadata documentation for an explanation.

const result = await rokka.sourceimages.meta.replace('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', {
  somefield: 'somevalue',
  'int:some_number': 0
})

rokka.sourceimages.meta.delete(organization, hash, [field=null])Promise<RokkaResponse>

Replace user metadata of a source image with the passed data.

See the user metadata documentation for an explanation.

await rokka.sourceimages.meta.delete('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a')

If the third parameter (field) is specified, it will just delete this field.

Sourceimages alias

Source Images alias

See the usource image alias documentation for more information.

rokka.sourceimages.alias.create(organization, alias, data, [params={}])Promise<RokkaResponse>

Adds an alias to a source image.

See the source image alias documentation for an explanation.

const result = await rokka.sourceimages.alias.create('myorg', 'myalias', {
  hash: 'somehash',
})

rokka.sourceimages.alias.get(organization, alias)Promise<RokkaResponse>

Get an alias.

rokka.sourceimages.alias.delete(organization, alias)Promise<RokkaResponse>

Delete an alias.

rokka.sourceimages.alias.invalidateCache(organization, alias)Promise<RokkaResponse>

Invalidate the CDN cache for an alias.

Operations

Available operations

  • rokka.operations.resize(width, height, options = {})
  • rokka.operations.autorotate(options = {})
  • rokka.operations.rotate(angle, options = {})
  • rokka.operations.dropshadow(options = {})
  • rokka.operations.trim(options = {})
  • rokka.operations.crop(width, height, options = {})
  • rokka.operations.noop()
  • rokka.operations.composition(width, height, mode, options = {})
  • rokka.operations.blur(sigma, radius)

Please refer to the rokka API documentation

rokka.operations.list()Promise<RokkaResponse>

Get a list of available stack operations.

const result = await rokka.operations.list()

Stackoptions

rokka.stackoptions.get()Promise<RokkaResponse>

Returns a json-schema like definition of options which can be set on a stack.

const result = await rokka.stackoptions.get()

Stacks

rokka.stacks.list(organization, [limit=null], [offset=null])Promise<RokkaResponse>

Get a list of available stacks.

const result = await rokka.stacks.list('myorg')

rokka.stacks.get(organization, name)Promise<RokkaResponse>

Get details about a stack.

const result = await rokka.stacks.get('myorg', 'mystack')

rokka.stacks.create(organization, name, stackConfig, [params={}])Promise<RokkaResponse>

Create a new stack.

The signature of this method changed in 0.27.

Using a single stack operation object (without an enclosing array) as the 3rd parameter (stackConfig) is since version 0.27.0 not supported anymore.

const operations = [
  rokka.operations.rotate(45),
  rokka.operations.resize(100, 100)
]

// stack options are optional
const options = {
  'jpg.quality': 80,
  'webp.quality': 80
}

// stack expressions are optional
const expressions = [
  rokka.expressions.default('options.dpr > 2', { 'jpg.quality': 60, 'webp.quality': 60 })
]

// query params are optional
const queryParams = { overwrite: true }
const result = await rokka.stacks.create(
  'test',
  'mystack',
  { operations, options, expressions },
  queryParams
)

rokka.stacks.delete(organization, name)Promise<RokkaResponse>

Delete a stack.

await rokka.stacks.delete('myorg', 'mystack')

rokka.stacks.invalidateCache(organization, name)Promise<RokkaResponse>

Invalidate the CDN cache for a stack.

See the caching documentation for more information.

await rokka.stacks.invalidateCache('myorg', 'mystack')

Render

rokka.render.getUrl(organization, hash, format, stack, [options])string

Get URL for rendering an image.

If you just need this function in a browser, you can also use rokka-render.js

rokka.render.getUrl('myorg', 'c421f4e8cefe0fd3aab22832f51e85bacda0a47a', 'png', 'mystack')

rokka.render.getUrlFromUrl(rokkaUrl, stack, [options={}])string

Get URL for rendering an image from a rokka render URL.

If you just need this function in a browser, you can also use rokka-render.js

rokka.render.getUrlFromUrl('https://myorg.rokka.io/dynamic/c421f4e8cefe0fd3aab22832f51e85bacda0a47a.png', 'mystack')

rokka.render.imagesByAlbum(organization, album, [options])Promise<RokkaResponse>

Get image hashes and some other info belonging to a album (from metadata: user:array:albums)

rokka.render.imagesByAlbum('myorg', 'Albumname', { favorites })

rokka.render.signUrl(url, signKey, options)string

Signs a Rokka URL with an option valid until date.

It also rounds up the date to the next 5 minutes (300 seconds) to improve CDN caching, can be changed

rokka.render.signUrlWithOptions(url, signKey, options)string

Signs a rokka URL with a sign key and optional signature options.

rokka.render.addStackVariables(url, variables, [removeSafeUrlFromQuery=false])Promise

Adds stack variables to a rokka URL in a safe way

Uses the v query parameter, if a variable shouldn't be in the path

If you just need this function in a browser, you can also use rokka-render.js

Stats

rokka.stats.get(organization, [from=null], [to=null])Promise<RokkaResponse>

Retrieve statistics about an organization.

If from and to are not specified, the API will return data for the last 30 days.

const result = await rokka.stats.get('myorg', '2017-01-01', '2017-01-31')

Request

rokka.request.request(path, [method='GET'], [body=null])Promise<RokkaResponse>

Does an authenticated request for any path to the Rokka API

Utils

rokka.utils.signUrl(organization, url, [options={}])Promise<RokkaResponse>

Sign a URL using the server-side signing endpoint.

This is useful when you don't have access to the signing key on the client side but want to generate signed URLs.

See the signing URLs documentation for more information.

const result = await rokka.utils.signUrl('myorg', 'https://myorg.rokka.io/dynamic/abc123.jpg')
console.log(result.body.signed_url)

Deploying to npm

To publish a new version of rokka.js to npm:

  1. Update the version in package.json

  2. Run tests to ensure everything works:

    npm test
  3. Build the distribution files:

    npm run compile
  4. Update the changelog (if applicable)

  5. Commit and tag the release:

    git add .
    git commit -m "chore: release vX.Y.Z"
    git tag vX.Y.Z
    git push origin master --tags
  6. Publish to npm:

    npm publish

Note: You need to be logged in to npm (npm login) and have publish rights to the rokka package.

About

The official JavaScript client library for rokka.io

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 8