guideDocument storage feature in Node.js

This article presents an example of an application that uses the document storage feature in Node.js and Express.js.

# Dependencies

This example uses the following dependencies:

  • axios
  • body-parser
  • cors
  • express

It also uses core dependecies from Node.js: path and fs.

# Example

The following example allows to upload an editor bundle, get a list of documents, get a document, and remove a document.

This file presents an example of a simple Express.js application.

Remember to provide a correct API secret and generate a proper request signature.

const path = require( 'path' );
const fs = require( 'fs' );
const express = require( 'express' );
const axios = require( 'axios' );
const cors = require( 'cors' );
const bodyParser = require( 'body-parser' );
const generateSignature = require( './utils/generateSignature' ); // See: https://ckeditor.com/docs/cs/latest/examples/security/request-signature-nodejs.html.
const editorBundle = fs.readFileSync( path.resolve( '../client/build/editor.js' ) ); // It should be your bundled editor.

const app = express();
const port = 8000; // The default application port.
const apiSecret = 'SECRET'; // Do not forget to hide this value in a safe place e.g. a .env file!

app.use( bodyParser.urlencoded( { extended: true } ) );
app.use( bodyParser.json() );
app.use( cors() );

// This function will be responsible for sending requests to CKEditor Cloud Services API.
async function sendRequest( method, url, body ) {
    const CSTimestamp = Date.now();
    const payload = {
        method,
        url,
        mode: 'no-cors',
        headers: {
            'Content-Type': 'application/json',
            'X-CS-Signature': generateSignature( apiSecret, method, url, CSTimestamp, body ),
            'X-CS-Timestamp': CSTimestamp
        }
    };

    if ( method.toUpperCase() !== 'GET' ) {
        payload.data = body;
    }

    try {
        const { status, data } = await axios( payload );

        return { status, data };
    } catch ( { response } ) {
        const { status, data } = response;

        return { status, data };
    }
}

// Upload the editor bundle. Note that you will need to upload your editor again if you change the bundle.
app.post( '/upload-editor', async ( req, res ) => {
    const { organizationId, environmentId, bundleVersion } = req.body;

    const { status, data } = await sendRequest( 'POST', `https://${ organizationId }.cke-cs.com/api/v4/${ environmentId }/editors`, {
        bundle: editorBundle.toString(),
        config: {
            cloudServices: {
                bundleVersion // This value should be unique per environment.
            }
        }
    } );

    return res.json( { status, data } );
} );

// Deletes a single document.
app.delete( '/documents/:documentId', async ( req, res ) => {
    const { organizationId, environmentId } = req.query;
    const { documentId } = req.params;

    const { status } = await sendRequest( 'DELETE', `https://${ organizationId }.cke-cs.com/api/v4/${ environmentId }/documents/${ documentId }` );

    return res.json( { status } );
} );

// Gets a single document.
app.get( '/documents/:documentId', async ( req, res ) => {
    const { organizationId, environmentId } = req.query;
    const { documentId } = req.params;

    const { status, data } = await sendRequest( 'GET', `https://${ organizationId }.cke-cs.com/api/v4/${ environmentId }/documents/${ documentId }` );

    return res.json( { status, data } );
} );

// Gets a list of documents.
app.get( '/documents', async ( req, res ) => {
    const { organizationId, environmentId} = req.query;

    const { status, data } = await sendRequest( 'GET', `https://${ organizationId }.cke-cs.com/api/v4/${ environmentId }/documents` );

    return res.json( { status, data } );
} );

app.listen( port, () => console.log( `The application is listening on port ${ port }!` ) );

# Usage

Run:

npm run start

Then by sending HTTP requests to this application you can perform actions and communicate with CKEditor Cloud Services. See the following example:

try {
    const response = await fetch( 'http://localhost:8000/upload-editor', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify( { environmentId, organizationId } )
    } );

    const data = await response.json();

    console.log( 'Result of uploading editor:', data );
} catch ( error ) {
    console.log( 'Error occurred:', error );
}