Using Ottoman.js and Express

  • Build a REST API with Couchbase’s proprietary Ottoman.js ODM
  • See how you can fetch data from Couchbase using SQL++ queries
  • Explore CRUD operations in action with Couchbase

In this tutorial, you will learn how to connect to a Couchbase cluster using Ottoman JS instead of the NodeJS SDK to create, read, update, and delete documents, and write simple parametrized SQL++ queries.

Prerequisiti

Per eseguire questo progetto preconfigurato, avrete bisogno di:

  • Couchbase Capella cluster with Travel-sample La carretta è carica.

    • Per eseguire questo tutorial utilizzando un cluster di Couchbase gestito autonomamente, si prega di consultare la documentazione relativa al comando appendice.
  • NodeJS & NPM

  • Caricamento del contenitore di campioni per il viaggio Se il file travel-sample non è stato caricato nel vostro cluster Capella, potete caricarlo seguendo le istruzioni per il vostro cluster Capella:

Note that this tutorial is designed to work with the latest Ottoman version (2) for Couchbase. It will not work with the older Ottoman versions for Couchbase without adapting the code.

Configurazione di Couchbase Capella

Quando si esegue Couchbase utilizzando Capella, Per poter utilizzare questo servizio, è necessario soddisfare i seguenti requisiti preliminari.

  • L'applicazione richiede che il bucket dei campioni di viaggio sia caricato nel cluster della Capella UI.
  • Creare il credenziali del database per accedere al bucket travel-sample (Read e Write) utilizzato nell'applicazione.
  • Consenti l'accesso al cluster dal IP su cui è in esecuzione l'applicazione.

Configurazione dell'applicazione

Cloning Repo

git clone https://github.com/couchbase-examples/ottomanjs-quickstart.git

Installare le dipendenze

Any dependencies will be installed by running the npm install command from the root directory of the project.

npm install

Configurazione della database di configurazione

Per saperne di più su come connettersi al cluster Capella, si prega di seguire le istruzioni riportate nella pagina dedicata. istruzioni.

In particolare, è necessario fare quanto segue:

All configuration for communication with the database is read from the environment variables. We have provided a convenience feature in this quickstart to read the environment variables from a local file, dev.env nel config cartella.

Creare una copia di config/dev.env.example file and rename it to config/dev.env and add the values for the Couchbase connection.

DB_CONN_STR=
DB_USERNAME=
DB_PASSWORD=

Nota: La stringa di connessione prevede couchbases:// o couchbase:// parte.

Lanciare l'applicazione

Direttamente sulla macchina locale

In questo momento abbiamo installato le dipendenze, caricato i dati del travel-sample e configurato l'applicazione con le credenziali. L'applicazione è ora pronta e potete lanciarla.

L'applicazione verrà eseguita sul port 3000 della macchina locale (http://localhost:3000). Troverete la documentazione Swagger sull'API che potete utilizzare per provare gli endpoint dell'API.

# Execute this command in the project's root directory
npm start

Docker

Se preferite eseguire questa rapida introduzione utilizzando Docker, abbiamo fornito il Dockerfile che potete utilizzare per creare l'immagine e eseguire l'API come container.

  • Creare l'immagine Docker
cd src
docker build -t couchbase-ottoman-quickstart .
  • Iniziare a eseguire l'immagine Docker
docker run -it --env-file config/dev.env -p 3000:3000 couchbase-ottoman-quickstart

Nota: Il config/dev.env Il file contiene le informazioni di connessione per connettersi al cluster Capella. Con il --env-file, docker iniettirà queste variabili di ambiente nel container.

Once the app is up and running, you can launch your browser and go to the Swagger documentation per testare le API.

Verificare l'applicazione

Una volta avviata l'applicazione, è possibile visualizzare i dettagli dell'applicazione nei log.

Application Startup

L'applicazione verrà eseguita sul port 3000 della macchina locale (http://localhost:3000). Potrete trovare la documentazione interattiva di Swagger per l'API accedendo all'URL nel vostro browser. La documentazione di Swagger viene utilizzata in questa demo per illustrare i diversi punti di accesso all'API e come essi possono essere chiamati. Ulteriori dettagli sulla documentazione di Swagger sono disponibili nella sezione appendice.

Swagger Documentation

Modello dei dati

Per questo tutorial utilizzeremo tre collezioni:, aeroporto, aerolinea e itinerario che contengono rispettivamente aeroporti campione, compagnie aeree e rotte aeree. La raccolta di rotte collega gli aeroporti e le compagnie aeree come mostrato nella figura sottostante. Usiamo queste connessioni nel quickstart per generare aeroporti direttamente collegati e compagnie aeree che collegano un aeroporto di destinazione. Nota che questi sono solo esempi per evidenziare come è possibile utilizzare le query SQL++ per aggregare le collezioni.

img

Proviamo a rivedere il codice

Per iniziare questo tutorial, clonate il repo e apriamolo nell'IDE di vostra scelta. Ora potete imparare come creare, leggere, aggiornare e cancellare documenti in Couchbase Server.

Layout del codice

├── src/controllers
│   ├── airlineController.js
│   ├── airportController.js
│   └── routeController.js
├── db
│   ├── ottomanConnection.js
├── src/routes
│   ├── airline.js
│   ├── airport.js
│   ├── route.js
├── src/shared
│   ├── makeResponse.js
├── src/app.js
├── src/server.js
├── Dockerfile
└── __test__


We have separated out the code into separate files by the entity (collection) in the controllers folder. The tests for the project are present in the __test__ cartella.

Entità aeroportuale

For this tutorial, we will focus on the airport entity. The other entities are similar.

Stabiliremo un'API REST per gestire i documenti aeroportuali.

Per le operazioni CRUD utilizzeremo il Ottoman JS, an object-document mapping built on top of the Couchbase NodeJS SDK to create, read, update, and delete a document. Every document will need an ID (similar to a primary key in other databases) to save it to the database. For other end points, we will use Ottoman Query API per richiedere documenti.

Document Structure

Our airport document will have an airportname, city, country, faa code, icao code, timezone info and the geographic coordinates. For this demo, we will store all airport information in one document in the aeroporto raccolta nel Travel-sample bucket.

{
  "airportname": "Sample Airport",
  "city": "Sample City",
  "country": "United Kingdom",
  "faa": "SAA",
  "icao": "SAAA",
  "tz": "Europe/Paris",
  "geo": {
    "lat": 48.864716,
    "lon": 2.349014,
    "alt": 92
  }
}

Creating an Ottoman Schema and Model for our Airport documents

To work with documents in Ottoman we must first set up our Schema e model, let’s take a look at the /models/airportModel.js before moving onto the App.js and related code:

import { model, Schema } from 'ottoman'

// Geo sub-schema
const GeoSchema = new Schema({
  alt: { type: Number },
  lat: { type: Number },
  lon: { type: Number },
});

const AirportSchema = new Schema({
  airportName: { type: String, required: true },
  city: { type: String, required: true },
  country: { type: String, required: true },
  faa: { type: String, required: true },
  geo: GeoSchema,
  icao: { type: String, required: false },
  tz: { type: String, required: false },
});

And finally we define our model using this Schema where we specify collectionName e keyGeneratorDelimiter as we do not plan on using the default which is :: on travel-sample bucket :

const AirportModel = model("airport", AirportSchema, {
  modelKey: "type",
  collectionName: "airport",
  keyGeneratorDelimiter: "_",
});

module.exports = {
  AirportModel,
};

Let’s go over the server.js e il App.js files located in the /src directory. Let’s open the server.js file first to see how it kicks off the application server and then the App.js file to learn about how we create, read, update and delete documents in our database.

src/server.js:

Il server.js file bootstraps our application, it imports some definitions from our app.js file, and connects to our server through ottoman.connect(). The call to ottoman.start() method is just a shortcut to run ensureCollections e ensureIndexes (Ottoman’s methods ensuring collections and indexes exist or get created by Ottoman).

Next, we start up the express application by listening to our desired port.

import { app, ottoman } from './app.js'

const startApiServer = async() => {
  try {
    await ottoman.connect({
      bucketName: process.env.CB_BUCKET,
      connectionString: process.env.CB_URL,
      username: process.env.CB_USER,
      password: process.env.CB_PASS,
    })
    // By default start function will wait for indexes, but you can disable it setting ignoreWatchIndexes to true. 
    // It's not required to execute the start method in order for Ottoman work.
    await ottoman.start()
    
    const port = process.env.APP_PORT
    app.listen(port, () => {
      console.log(`API started at http://localhost:${port}`)
      console.log(`API docs at http://localhost:${port}/api-docs/`)
    })
  } catch (e) {
    console.log(e)
  }
}

startApiServer()

src/app.js:

We import our dependencies and database connection:

import express from "express";
import cors from "cors";
import { ottoman, Query } from "../db/ottomanConnection";
import airlineRoutes from "./routes/airline";
import airportRoutes from "./routes/airport";
import route from "./routes/route";
import swaggerUi from "swagger-ui-express";
import YAML from "yamljs";

One of our import statements in this file pulls in: /db/ottomanConnection.js. This gives us access to some of the Ottoman resources we need for our endpoints to persist data to Couchbase.

import { Ottoman, getOttomanInstances, getDefaultInstance, ValidationError, FindOptions, SearchConsistency,Query } from 'ottoman'

const ottoman = new Ottoman({
  modelKey: 'type',
  scopeName: 'inventory'
})

module.exports = { ottoman, getOttomanInstances, getDefaultInstance, ValidationError, FindOptions, SearchConsistency,Query }

Nel ottomanConnection.js file in the db folder, we forward the assets from Ottoman that we will use in App.js.


After we have our configuration for database connection in place, we can create our express app:

const app = express()

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

Shared Directory

Apri src/shared folder and navigate to the makeResponse.js which contains a asynchronous function makeResponse for handling Express responses, executing provided actions, and managing errors. It specifically logs errors, sets appropriate HTTP status codes, and responds with a JSON object containing the error message. The status code is determined based on whether the error is a ValidationError or contains the string “not found.”

import { ValidationError} from '../../db/ottomanConnection'

async function makeResponse(res, action) {
  try {
    const result = await action()
    res.json(result)
  } catch (e) {
    const status = e.message !== undefined && e.message.indexOf('not found') !== -1 ? 404 : 500
    res.status(e instanceof ValidationError ? 400 : status)
    res.json({ message: e.message })
  }
}

module.exports = {
  makeResponse
}

Aeroporto POST

To insert a new airport document, locate the createAirline method within the airportController file found in the controllers package. This expects a POST request with the airport data provided in the request body. We extract this airport ID from the airport data, check if there is a document with the same key, and create a airport document using Ottoman’s .save() method and our model named: AirlineModel.

  try {
    // Try to find an existing document with the given ID
    const existingAirline = await AirlineModel.findById(req.body.id);

    if (existingAirline) {
      // Document with the same id already exists
      return res.status(409).json({ message: "Duplicate key error" });
    }
  } catch (error) {
    // Ignore the error (i.e document with key not found, proceed to create)
  }
  await makeResponse(res, async () => {
    const airline = new AirlineModel(req.body);
    await airline.save();
    res.status(201);
    return airline;
  });

Let’s break this code down.

After we check for required body parameters, we create a call to the makeResponse() to handle a call to ottoman’s save(). We create a airport document with airport.save() and the airport it uses confirms to its Ottoman model called airportModel.

GET Airport

To fetch a airport document, locate the getAirport method within the airportController.js file found in the controllers package. This expects a GET request with the airport document ID (id) specified in the URL path. We extract this airport document ID from the URL and retrieve a Airport document using Ottoman’s .findById() method using the AirportModel.

  await makeResponse(res, async () => {
    const airline = await AirlineModel.findById(req.params.id);
    return airline;
  });

We only need the airport ID from the user to retrieve a particular airport document using a basic key-value operation. We catch the error if the key-value operation fails and return an error message.

Aeroporto di PUT

To update a airport document, locate the updateAirline method within the airportController.js file found in the controllers package. This expects a PUT request with the airport ID (id) specified in the URL path and the airport data to be updated provided in the request body.

  await makeResponse(res, async () => {
    const airline = AirlineModel.replaceById(req.body.id, req.body);
    return airline;
  });

Il UpdateAirport method chiama il replaceyId() metodo.

DELETE Airport

To delete a airport document, locate the DeleteDocumentForAirport method within the airportController.js file found in the controllers package. This expects a DELETE request with the airport document ID (id) specified in the URL path. We just need to supply the id of the document we want to remove.

  await makeResponse(res, async () => {
    await AirlineModel.removeById(req.params.id);
    res.status(204);
  });

Delete Airport by Airport ID by using Ottoman’s removeById() Il metodo sulla AirportModel and returns a 404 if the document is not found.

Lista aeroporti

Questo endpoint recupera l'elenco degli aeroporti presenti nel database. L'API offre la possibilità di specificare la dimensione della pagina dei risultati e il paese da cui estrarre i documenti relativi agli aeroporti.

SQL++ is a powerful query language based on SQL, but designed for structured and flexible JSON documents. We will use a SQL+ query to search for airports with Limit, Offset, and Country option. The SQL++ query is built using the models find method.

Navigare fino alla listAirports il metodo nel airportController.js file. Questo endpoint è diverso dagli altri che abbiamo visto in precedenza perché esegue una query SQL++ anziché una operazione chiave-valore. Ciò comporta solitamente un aumento dell'overhead poiché è coinvolto il motore di query. Per questa query, utilizziamo gli indici predefiniti presenti nel file Travel-sample bucket. Possiamo creare un altro indice specifico per questa query per renderla più efficiente.

First, we need to get the values from the query string for country, limit, and Offset that we will use in our query. These are pulled from the request.query metodo.

Questo endpoint ha due query a seconda del valore del parametro Paese. Se viene specificato un nome di paese, recuperiamo i documenti relativi all’aeroporto per quel paese specifico. Se non viene specificato, recuperiamo l’elenco degli aeroporti di tutti i paesi. Le query sono leggermente diverse per questi due scenari.

The Ottoman’s find() method takes the paramters we received from the user as options.

  const country = req.query.country || "";
  const limit = parseInt(req.query.limit, 10) || 10;
  const offset = parseInt(req.query.offset, 10) || 0;
  let filter = {};
  if (country) {
    filter.country = country;
  }

  const options = { limit: limit, offset: offset };
  await makeResponse(res, async () => {
    const airports = await AirportModel.find(filter, options);
    return airports.rows;
  });

Connessioni dirette

This endpoint fetches the airports that can be reached directly from the specified source airport code. This uses the query builder to create the SQL++ query and fetch the results simlar to the List Airport endpoint but uses the ottoman instance to query the result via the query builder by first creating the sub query and then using the build method on it.

Let us look at the sub query being created here:

  const airport = req.query.airport;
  const limit = parseInt(req.query.limit, 10) || 10;
  const offset = parseInt(req.query.offset, 10) || 0;
  // Subquery to get distinct airline IDs
  const subquery = new Query({}, "travel-sample.inventory.route")
    .select([{ $field: "DISTINCT route.destinationairport" }])
    .plainJoin(
      "JOIN `travel-sample`.inventory.airport AS airport ON route.sourceairport = airport.faa",
    )
    .where({
      "airport.faa": { $eq: airport },
      "route.stops": { $eq: 0 },
    })
    .orderBy({ "route.destinationairport": "ASC" })
    .limit(limit)
    .offset(offset);

  await makeResponse(res, async () => {
    const result = await ottoman.query(subquery.build());
    return result.rows;
  });

Raccogliamo le connessioni dirette unendo la raccolta dell'aeroporto alla raccolta del percorso e filtrando in base all'aeroporto di origine specificato dall'utente e alle rotte senza fermate.

Project Setup Notes

We have set up a .babelrc file at the root of our project so that we can use ES6 and imports in our project:

{
  "presets": [
    "@babel/preset-env"
  ]
}

We have created a start script in our package.json that executes babel-node and the starting point of our application src/server.js:

"scripts": {
  "start": "env-cmd ./config/dev.env nodemon --exec babel-node src/server",
},

There are other scripts that we have added for our maintenance and testing of the project on GitHub using GitHub actions.

  "scripts": {
    "start": "env-cmd -f ./config/dev.env nodemon --exec babel-node src/server",
    "test": "env-cmd -f ./config/test.env jest --verbose --forceExit --detectOpenHandles",
    "testGA": "jest --verbose --runInBand",
    "clean": "rm -rf dist",
    "build": "npm run clean && babel ./src --out-dir dist --copy-files"
  },

Esecuzione dei test

Abbiamo definito i test di integrazione utilizzando jest for all the API end points. The integration tests use the same database configuration as the application. After the tests, the documents are cleaned up.

The tests are configured in the __test__ cartella.

To run the tests, create a copy of config/test.env.example file and rename it to config/test.env and add the values for the Couchbase connection.

# Execute this command in the project's root directory
npm run test

Appendice

Ampliare l'API aggiungendo un'entità nuova

Se desiderate aggiungere un'altra entità alle API, i passaggi da seguire sono i seguenti:

  • Create the New Entity in Couchbase Bucket:

  • Define the New Route:

    • Navigare fino alla src/routes folder and create the new route.
  • Controller Configuration:

    • Develop a new file in the controllers folder, mirroring the existing structures (e.g., airportController.js). Craft the corresponding method within this file to manage the new entity.
  • Add Tests:

    • Aggiungere i test per le nuove rotte in un nuovo file nel __test__ folder similar to other collection tests.

Following these steps ensures a systematic and organized approach to expanding the API functionality with a new entity.

Gestione automatica di un cluster di Couchbase

Se stai eseguendo questo quickstart con un cluster di Couchbase gestito autonomamente, è necessario caricare caricare i dati del bucket dei dati di viaggio nel cluster e generare le credenziali per il bucket.

È necessario aggiornare la stringa di connessione e le credenziali nel file dev.env file in the config cartella.

Note: Couchbase Server must be installed and running prior to running the app.

Documentazione Swagger

La documentazione di Swagger fornisce una panoramica chiara dell'API, includendo endpoint, metodi HTTP, parametri delle richieste e oggetti di risposta.

Fare clic su un singolo endpoint per ampliarlo e visualizzare le informazioni dettagliate. Ciò include la descrizione dell’endpoint, i possibili codici di stato delle risposte e i parametri della richiesta che esso accetta.

Testare l'API

È possibile provare un'API cliccando sul pulsante “Prova” accanto agli endpoint.

  • Parametri: Se un endpoint richiede parametri, l'interfaccia utente Swagger fornisce dei campi di input da compilare. Questi possono includere parametri di percorso, stringhe di query, intestazioni o il corpo di una richiesta POST/PUT.

  • Esecuzione: Una volta inseriti tutti i parametri necessari, è possibile cliccare sul pulsante “Esecuzione” per effettuare una chiamata API in tempo reale. L’interfaccia utente Swagger invierà la richiesta all’API e visualizzerà la risposta direttamente nella documentazione. Ciò include il codice della risposta, gli header e il corpo della risposta.

Modelli

Swagger documenta la struttura dei corpi di richiesta e risposta utilizzando modelli. Questi modelli definiscono la struttura dei dati prevista utilizzando lo schema JSON e sono estremamente utili per comprendere quali dati inviare e quali aspettarsi.

Lasciare la proliferazione dei database nel passato

Ogni aggiunta di stack significa un altro conto da gestire. Calcola in 2 minuti quanto puoi risparmiare.