Start typing to search...

@withkoji/database (deprecated)

Warning

This package is deprecated and is included only for backwards compatibility. For new templates, use withkoji-koji-core.html.

Each Koji project includes a key-value store that you can use as a backend database for simple use cases, such as collecting information from users, aggregating survey or poll results, and creating leaderboards for games. Koji databases are made up of one or more collections. Each collection stores a series of database entries with a unique key and collection of key-value pairs. Values within the key-value pairs can be of any type, including strings, numbers, and arrays.

The @withkoji/database package enables you to implement a Koji database for the backend of your template. In immediate mode (default), you send database updates one request at a time. In transaction mode, you can batch several updates together by calling beginTransaction, calling the request methods, and then calling commitTransaction to submit the batch.

Install

Install the package in the backend service of your Koji project.

Warning
  • To maintain adequate read/write security, your template must connect to the database only from a backend route.

  • To support instant remixes of your template, you must also install the withkoji-vcc-package.html package and implement the VccMiddleware on your backend server. This middleware maintains the environment variables for instant remixes, ensuring that database access is restricted to the correct remix version.

cd backend
npm install --save @withkoji/database

valueTypes

The valueTypes object provides atomic operations as static methods that can be used with database requests.

.increment(number)

Increments a numeric value by a specified amount. You can use this method to increment numeric values in the database with a single request. See update.

Parameters

  • numberNumber, the amount to increment the value.

Example

const updated = await database.update('collection', 'document', {
    'myValue': Database.valueTypes.increment(1),
});

Database

new Database(config, mode)

Instantiates Database.

Parameters

  • config – (Required for instant remix support) Object, environment variables that serve as access credentials. Contains the following properties:

    • projectIDString, unique identifier for the Koji.

    • projectTokenString, secret key for the Koji.

    Tip
    For templates that support instant remixes, you must implement VccMiddleware to manage these variables. See withkoji-vcc-package.html.
  • mode – (Optional) String, when to send updates to the database. Use one of the following modes:

Example

import Database from '@withkoji/Database';
const database = new Database({
  projectId: res.locals.KOJI_PROJECT_ID,
  projectToken: res.locals.KOJI_PROJECT_TOKEN,
});

Database methods

.arrayPush(collection, key, data)

Adds data onto arrays in an existing database entry.

Note
If the data you attempt to push onto an array is already present, it will not be added again.

Parameters

  • collectionString, name of the collection.

  • keyString, key for the database entry.

  • dataAny, key-value pairs of arrays and the entries to add to them.

Returns

(Async) Boolean, indicates whether the data was successfully added to the specified arrays.

Example

const isAdded = await database.arrayPush('myCollection', 'myExistingKey', {'myArray1':'myValue1', 'myArray2': 'myValue2'});

.arrayRemove(collection, key, data)

Removes data from arrays in an existing database entry.

Parameters

  • collectionString, name of the collection

  • keyString, key for the database entry.

  • dataAny, key-value pairs of arrays and the entries to remove from them.

Returns

(Async) Boolean, indicates whether the data was successfully removed from the specified arrays.

Example

const isRemoved = await database.arrayRemove('myCollection', 'myExistingKey', {'myArray1':'myValue1', 'myArray2': 'myValue2'});

.beginTransaction()

Creates a new transaction for sending one or more updates to the database in a batch.

Warning
Available in transaction mode only. See withkoji-database-package.html#new%20Database.

Example

database.beginTransaction();

.commitTransaction()

(Async) Submits a batch of update requests to the database in a single transaction.

Warning
Available in transaction mode only. See withkoji-database-package.html#new%20Database.

Example

await database.commitTransaction();

.delete(collection, key)

Deletes an entire entry from the database.

Parameters

  • collectionString, name of the collection.

  • keyString, key of the database entry.

Returns

(Async) Boolean, indicates whether the entry was successfully deleted.

Example

const isDeleted = await database.delete('myCollection', 'myExistingKey');

.generateSignedUploadRequest(fileName)

Generates a signed URL for uploading a file directly to your project’s CDN. For an in-depth guide to this method, see frontend-uploading.html.

Note
The size limit for this method is 150MB per uploaded file.
Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • fileNameString, name of the file to upload.

Returns

(Async) SignedUploadRequest, structured data of the signed request with the following structure:

interface SignedUploadRequest {
  url: string,
  signedRequest: {
    url: string,
    fields: {[index: string]: string};
  };
}

Example

const signedUpload = await database.generateSignedUploadRequest("fileName");

.get(collection, key)

Gets the specified database entry or collection of entries.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • collectionString, name of the collection.

  • key – (Optional) String, key of the database entry.

Returns

(Async) Object, the requested values from the collection.

Example

const myData = await database.get('myCollection');
const myValue = await database.get('myCollection','myKey');

.getAll(collection, keys)

Gets all the specified database entries.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • collectionString, name of the collection.

  • keys – Array of Strings, list of keys of the database entries to retrieve.

Returns

(Async) Array of Objects, the requested database entries from the collection.

Example

const myValue = await database.getAll('myCollection',['myKey1', 'myKey2']);

.getAllWhere(collection, predicateKey, predicateOperation, predicateValues)

Gets all the database entries that match a query against a list of possible values.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • collectionString, name of the collection.

  • predicateKeyString, key of the data to query.

  • predicateOperationString, operator to use for the query. Possible values are <, <=, ==, >, >=.

  • predicateValues – Array of Strings, list of values to run the query against. Database entries need to match one or more of these values to be returned.

Returns

(Async) Array of Objects, database entries that match the queries of at least one predicateValue.

Example

const results = await database.getAllWhere('myCollection','predicateKey', '==', ['predicateValue1', 'predicateValue2']);

.getCollections()

Gets a list of all collections available in the database.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Returns

(Async) Array of Strings, list containing the names of the collections.

Example

const collections = await database.getCollections();

.getWhere(collection, predicateKey, predicateOperation, predicateValue)

Gets all the database entries that match a query against a value.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • collectionString, name of the collection.

  • predicateKeyString, key of the data to query.

  • predicateOperationString, operator to use for the query. Possible values are <, <=, ==, >, >=.

  • predicateValueString, value to run the query against.

Returns

(Async) Array of Objects, list of the database entries that match the query.

Example

const results = await database.getWhere('myCollection','predicateKey', '==', 'predicateValue');

.getTranscodeStatus(callbackToken)

Gets the status of transcoding for an asset that was requested with transcodeAsset.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • callbackTokenString, token identifying the asset. Returned by transcodeAsset when transcoding is requested.

Returns

(Async) Boolean, indicates whether transcoding has completed.

Example

await new Promise((resolve: any) => {
  const checkStatus = async () => {
    const { isFinished } = await database.getTranscodeStatus(transcodedVideo.callbackToken);
    if (isFinished) {
      resolve();
    } else {
      setTimeout(() => checkStatus(), 500);
    }
  };

  checkStatus();
});

.search(collection, searchAttribute, searchValue)

Returns all the database entries where the value of searchAttribute partially matches searchValue.

Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • collectionString, name of the collection.

  • searchAttributeString, key to partially match against.

  • searchValueString, value for the partial match.

Returns

(Async) Array of Objects, list of database entries that have a partial match.

Example

const results = await database.search('myCollection','myKey', 'myValue');

.set(collection, key, value)

Adds an entry to the database.

Parameters

  • collectionString, name of the collection.

  • keyString, key of the database entry.

  • dataAny, key-value pairs to add to the database.

Returns

(Async) Boolean, indicates whether the entry was successfully added.

Example

const isAdded = await database.set('myCollection', 'myKey', {'myValue':1});

.transcodeAsset(path, transcodeType)

Transcodes an asset that has been uploaded to the Koji CDN.

Note
Video transcoding usually completes in a few seconds, but can take longer depending on the length of the video. You can use getTranscodeStatus to poll for transcode progress.
Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • pathString, URL of the asset on the Koji CDN. For example, https://objects.koji-cdn.com/KOJI-ID/userData/resource.mp4.

  • transcodeTypeString, (Optional) type of resource that the asset will be transcoded to (video+hls).

Returns

(Async) Object, contains the following properties:

  • urlString, URL of the transcoded asset.

  • callbackTokenString, token identifying the asset. Use this token with getTranscodeStatus to check whether transcoding has completed.

Example

const transcodedVideo = await database.transcodeAsset(path);

.update(collection, key, data)

Updates an entry in the database with the given value. To increment numeric values with a single update request, you can use increment.

Note
This method updates only the values specified in data. If additional values exist for the key, they are not changed.

Parameters

  • collectionString, name of the collection.

  • keyString, key for the database entry.

  • dataAny, key-value pairs to update on the value.

Returns

(Async) Boolean, indicates whether the update was successful.

Example

const updated = await database.update('myCollection','myKey', {'myValue':2});

// To increment the numeric value in `myValue`
const updated = await database.update('collection', 'document', {
    'myValue': Database.valueTypes.increment(1),
});

.uploadFile(path, filename, mimetype)

Warning
Deprecated. Use generateSignedUploadRequest for new and upgraded templates.

Uploads files to your project’s CDN. For example, images, profile pictures, and audio.

Note
The size limit for this method is 10MB per uploaded file.
Warning
Available in immediate mode only. See withkoji-database-package.html#new%20Database.

Parameters

  • pathString, path to the file.

  • filename – (Optional) String, name for the uploaded file.

  • mimetype – (Optional) String, content type of the file.

Returns

(Async) String, Unique URL on images.koji-cdn.com or objects.koji-cdn.com, depending on the type of file.

Note
To prevent collisions, the specified filename is automatically modified to include a random string.

Example

const uploadedUrl = database.uploadFile(path, filename, mimetype);