Service examples for Node.js

Elasticsearch Sample Code

Source

const elasticsearch = require("elasticsearch");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("elasticsearch");

    const client = new elasticsearch.Client({
        host: `${credentials.host}:${credentials.port}`,
    });

    const index = "my_index";
    const type = "People";

    // Index a few document.
    const names = ["Ada Lovelace", "Alonzo Church", "Barbara Liskov"];

    const message = {
        refresh: "wait_for",
        body: names.flatMap((name) => [
            { index: { _index: index, _type: type } },
            { name },
        ]),
    };

    await client.bulk(message);

    // Search for documents.
    const response = await client.search({
        index,
        q: "name:Barbara Liskov",
    });

    const outputRows = response.hits.hits
        .map(
            ({ _id: id, _source: { name } }) =>
                `<tr><td>${id}</td><td>${name}</td></tr>\n`
        )
        .join("\n");

    // Clean up after ourselves.
    await Promise.allSettled(
        response.hits.hits.map(({ _id: id }) =>
            client.delete({
                index: index,
                type: type,
                id,
            })
        )
    );

    return `
    <table>
        <thead>
            <tr>
                <th>ID</th><th>Name</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};

Output

IDName
VLGD6pUB4Y_uW66_r8MbBarbara Liskov
InfluxDB Sample Code

Source

const Influx = require("influx");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const {
        username = "admin",
        password = "admin",
        host,
        port,
    } = config.credentials("influxdb");

    const influx = new Influx.InfluxDB(
        `http://${username}:${password}@${host}:${port}/deploys`
    );

    await influx.createDatabase("deploys");

    await influx.writePoints([
        {
            measurement: "deploy_time",
            tags: { host: "server01", region: "us-west" },
            fields: { value: 0.64, cpuCount: 10 },
            timestamp: new Date(2020, 10, 9, 10),
        },
        {
            measurement: "deploy_time",
            tags: { host: "server01", region: "us-west" },
            fields: { value: 0.84, cpuCount: 10 },
            timestamp: new Date(2020, 10, 9, 10, 30),
        },
    ]);

    const result = await influx.query(`select * from deploy_time`);

    await influx.dropDatabase("deploys");

    const outputRows = result
        .map(({ value, time }) => `<tr><td>${time}</td><td>${value}</td></tr>`)
        .join("\n");

    return `
    <table>
        <thead>
            <tr>
                <th>Timestamp</th><th>Value</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};

Output

undefined
Memcached Sample Code

Source

const Memcached = require('memcached');
const config = require("platformsh-config").config();
const { promisify } = require('util');

exports.usageExample = async function() {
    const credentials = config.credentials('memcached');
    const client = new Memcached(`${credentials.host}:${credentials.port}`);

    // The MemcacheD client is not Promise-aware, so make it so.
    const memcachedGet = promisify(client.get).bind(client);
    const memcachedSet = promisify(client.set).bind(client);

    const key = 'Deploy-day';
    const value = 'Friday';

    // Set a value.
    await memcachedSet(key, value, 10);

    // Read it back.
    const test = await memcachedGet(key);

    return `Found value <strong>${test}</strong> for key <strong>${key}</strong>.`;
};

Output

Found value Friday for key Deploy-day.
MongoDB Sample Code

Source

const mongodb = require("mongodb");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("mongodb");
    const MongoClient = mongodb.MongoClient;

    const client = await MongoClient.connect(
        config.formattedCredentials("mongodb", "mongodb")
    );

    const db = client.db(credentials["path"]);

    const collection = db.collection("startrek");

    const documents = [
        { name: "James Kirk", rank: "Admiral" },
        { name: "Jean-Luc Picard", rank: "Captain" },
        { name: "Benjamin Sisko", rank: "Prophet" },
        { name: "Katheryn Janeway", rank: "Captain" },
    ];

    await collection.insertMany(documents, { w: 1 });

    const result = await collection.find({ rank: "Captain" }).toArray();

    const outputRows = Object.values(result)
        .map(({ name, rank }) => `<tr><td>${name}</td><td>${rank}</td></tr>\n`)
        .join("\n");

    // Clean up after ourselves.
    collection.deleteMany();

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>Rank</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};

Output

NameRank
Jean-Luc PicardCaptain
Katheryn JanewayCaptain
MySQL Sample Code

Source

const mysql = require("mysql2/promise");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("database");

    const connection = await mysql.createConnection({
        host: credentials.host,
        port: credentials.port,
        user: credentials.username,
        password: credentials.password,
        database: credentials.path,
    });

    // Creating a table.
    await connection.query(
        `CREATE TABLE IF NOT EXISTS People (
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(30) NOT NULL,
            city VARCHAR(30) NOT NULL
        )`
    );

    // Insert data.
    await connection.query(
        `INSERT INTO People (name, city)
        VALUES
            ('Neil Armstrong', 'Moon'),
            ('Buzz Aldrin', 'Glen Ridge'),
            ('Sally Ride', 'La Jolla');`
    );

    // Show table.
    const [rows] = await connection.query("SELECT * FROM People");

    // Drop table.
    await connection.query("DROP TABLE People");

    const outputRows = rows
        .map(({ name, city }) => `<tr><td>${name}</td><td>${city}</td></tr>\n`)
        .join("\n");

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>City</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};

Output

NameCity
Neil ArmstrongMoon
Buzz AldrinGlen Ridge
Sally RideLa Jolla
OpenSearch Sample Code

Source

const { Client } = require("@opensearch-project/opensearch");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("opensearch");

    const client = new Client({
        node: `${credentials.scheme}://${credentials.host}:${credentials.port}`,
    });

    const indexName = "my_index";

    // Index a few document.
    const names = ["Ada Lovelace", "Alonzo Church", "Barbara Liskov"];

    if(!await client.indices.exists({index: indexName})) {
        var response = await client.indices.create({
            index: indexName,
        });
    }

    names.forEach(name => {
        client.index({
            index: indexName,
            body: {
                name: name
            },
            refresh: "wait_for"
        })
    })

    const query = {
        query: {
          match: {
            name: {
              query: "Barbara Liskov",
            },
          },
        },
      };
    

    // Search for documents.
    var response = await client.search({
        index: indexName,
        body: query,
    });

    const outputRows = response.body.hits.hits
        .map(
            ({ _id: id, _source: { name } }) =>
                `<tr><td>${id}</td><td>${name}</td></tr>\n`
        )
        .join("\n");

    // Clean up after ourselves.
    await Promise.allSettled(
        response.body.hits.hits.map(({ _id: id }) =>
            client.delete({
                index: indexName,
                id,
            })
        )
    );

    return `
    <table>
        <thead>
            <tr>
                <th>ID</th><th>Name</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};

Output

IDName
fZef6JUBofEkzYn2c4VfBarbara Liskov
PostgreSQL Sample Code

Source

const pg = require("pg");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const credentials = config.credentials("postgresql");

    const client = new pg.Client({
        host: credentials.host,
        port: credentials.port,
        user: credentials.username,
        password: credentials.password,
        database: credentials.path,
    });

    client.connect();

    // Creating a table.
    await client.query(
        `CREATE TABLE IF NOT EXISTS People (
            id SERIAL PRIMARY KEY,
            name VARCHAR(30) NOT NULL,
            city VARCHAR(30) NOT NULL
        )`
    );

    // Insert data.
    await client.query(
        `INSERT INTO People (name, city)
        VALUES
            ('Neil Armstrong', 'Moon'),
            ('Buzz Aldrin', 'Glen Ridge'),
            ('Sally Ride', 'La Jolla');`
    );

    // Show table.
    const result = await client.query("SELECT * FROM People");

    // Drop table.
    await client.query("DROP TABLE People");

    const outputRows = result.rows
        .map(({ name, city }) => `<tr><td>${name}</td><td>${city}</td></tr>\n`)
        .join("\n");

    return `
    <table>
        <thead>
            <tr>
                <th>Name</th><th>City</th>
            </tr>
        </thhead>
        <tbody>
            ${outputRows}
        </tbody>
    </table>
    `;
};

Output

NameCity
Neil ArmstrongMoon
Buzz AldrinGlen Ridge
Sally RideLa Jolla
Redis Sample Code

Source

const redis = require('redis');
const config = require("platformsh-config").config();
const { promisify } = require('util');

exports.usageExample = async function() {
    const credentials = config.credentials('redis');
    const client = redis.createClient(credentials.port, credentials.host);

    // The Redis client is not Promise-aware, so make it so.
    const redisGet = promisify(client.get).bind(client);
    const redisSet = promisify(client.set).bind(client);

    const key = 'Deploy day';
    const value = 'Friday';

    // Set a value.
    await redisSet(key, value);

    // Read it back.
    const test = await redisGet(key);

    return `Found value <strong>${test}</strong> for key <strong>${key}</strong>.`;
};

Output

Found value Friday for key Deploy day.
Solr Sample Code

Source

const solr = require("solr-node");
const config = require("platformsh-config").config();

exports.usageExample = async function () {
    const client = new solr(config.formattedCredentials("solr", "solr-node"));

    // Add a document.
    const addResult = await client.update({
        id: 123,
        name: "Valentina Tereshkova",
    });

    // Flush writes so that we can query against them.
    await client.softCommit();

    // Select one document:
    const strQuery = client.query().q();
    const writeResult = await client.search(strQuery);

    // Delete one document.
    const deleteResult = await client.delete({ id: 123 });

    return `
    Adding one document. Status (0 is success): ${addResult.responseHeader.status}<br />
    Selecting documents (1 expected): ${writeResult.response.numFound}<br />
    Deleting one document. Status (0 is success): ${deleteResult.responseHeader.status}<br />
    `;
};

Output

Adding one document. Status (0 is success): 0
Selecting documents (1 expected): 1
Deleting one document. Status (0 is success): 0