guideImport and export feature in Node.js

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

# Dependencies

This example uses the following dependencies:

  • axios
  • body-parser
  • cors
  • express

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

# Example

The following example allows you to upload an editor bundle, import the document data to CKEditor Cloud Services, and export the collaboration content.

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

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

// index.js
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/ckeditor.js' ) ); // This should be your bundled editor.

const app = express();
const port = 8000; // The default application port.
const bundleVersion = 'bundleVersion'; // This value should be unique per environment.
const apiSecret = 'SECRET'; // Do not forget to hide this value in a safe place e.g. an .env file!
const organizationId = 'organizationId'; // Type your organization ID here.
const environmentId = 'environmentId'; // Type your environment ID here.
// If you use On-Premises application you can adjust baseApiUrl accordingly with your application URL.
const baseApiUrl = `https://${ organizationId }.cke-cs.com/api/v5/${ environmentId }`;

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 { bundleVersion } = req.body;

    const { status, data } = await sendRequest( 'POST', `${ baseApiUrl }/editors`, {
        bundle: editorBundle.toString(),
        config: {
            cloudServices: {
                bundleVersion
            }
        }
    } );

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

// Import content to the document.
app.post( '/import', async ( req, res ) => {
    const { documentId, documentContent, bundleVersion } = req.body;

    const { status, data } = await sendRequest( 'POST', `${ baseApiUrl }/collaborations`, {
        document_id: documentId,
        bundle_version: bundleVersion,
        data: documentContent
    } );

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

// Export your data from CKEditor Cloud Services. You can schedule export operations e.g. once per hour.
app.get( '/export/:documentId', async ( req, res ) => {
    const { documentId } = req.params;

    const { status, data } = await sendRequest( 'GET', `${ baseApiUrl }/collaborations/${ documentId }` );

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

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

# Usage

Run:

node index.js

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

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

    const data = await response.json();

    console.log( 'Result of uploading editor:', data );
} catch ( error ) {
    console.log( 'Error occurred:', error );
}
  1. Importing the collaboration session.
try {
    const response = await fetch( 'http://localhost:8000/import', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify( { 
            bundleVersion,
            documentId: 'document-1',
            documentContent: '<p>Lorem Ipsum is <b>simply dummy</b> text of the printing and typesetting industry.</p>',
        } )
    } );

    const data = await response.json();

    console.log( 'Result of importing collaborative editing session:', data );
} catch ( error ) {
    console.log( 'Error occurred:', error );
}
  1. Exporting the collaboration session. The content imported in step 2 should be returned.
try {
    const response = await fetch( `http://localhost:8000/export/document-1`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    } );

    const data = await response.json();

    console.log( 'Result of exporting collaborative editing session:', data );
} catch ( error ) {
    console.log( 'Error occurred:', error );
}