In questo tutorial imparerai come connetterti a un cluster di Couchbase Capella per creare, leggere, aggiornare e cancellare documenti e come scrivere semplici query SQL++ parametrizzate.
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.
-
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 Node SDK version (4.x) for Couchbase. It will not work with the older Node.js 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/typescript-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:
- 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.
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.
This tutorial assumes that the APP_PORT variable in the configuration is set to 3000.
DB_CONN_STR=
DB_USERNAME=
DB_PASSWORD=
Nota: La stringa di connessione prevede
couchbases://ocouchbase://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.
The application will run on your local machine (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
# Execute this command in the project's root directory
docker build -t couchbase-typescriptjs-quickstart .
- Iniziare a eseguire l'immagine Docker
# Execute this command in the project's root directory.
docker run -it --env-file config/dev.env -p 3000:3000 couchbase-typescript-express-js-quickstart
Nota: Il
config/dev.envIl 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.

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.

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.

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.ts
│ ├── airportController.ts
│ └── routeController.ts
├── db
│ ├── connection.ts
├── errors
│ ├── errors.go
├── src/routes
│ ├── airline.ts
│ ├── airport.ts
│ ├── route.ts
├── src/shared
│ ├── makeResponse.ts
│ ├── validateRequiredField.ts
├── src/app.ts
├── src/server.ts
├── 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.
- Aeroporto POST – Creare un nuovo aeroporto
- GET Airport – Leggere l'aeroporto specificato
- Aeroporto di PUT – Aggiornamento aeroporto specificato
- DELETE Airport – Eliminare l'aeroporto
- Elenco degli aeroporti – Raccogliere tutti gli aeroporti. Opzionalmente è possibile filtrare l’elenco per paese
- Connessioni dirette – Ottieni una lista di aeroporti direttamente collegati all'aeroporto specificato
Per le operazioni CRUD utilizzeremo il Node JS 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.
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
}
}
Navigare fino alla connection.ts nel db folder. We perform some basic required checks for the environment variable not being set in the dev.env, and then proceed to connect to the couchbase cluster. We connect to the cluster using connettersi metodo.
async function createCouchbaseCluster(): Promise<couchbase.Cluster> {
if (cached.conn) {
return cached.conn;
}
const cluster = await couchbase.connect(DB_CONN_STR, {
username: DB_USERNAME,
password: DB_PASSWORD,
configProfile: "wanDevelopment",
});
cached.conn = cluster;
return cluster;
}
const airlineCollection = scope.collection("airline");
const airportCollection = scope.collection("airport");
const routeCollection = scope.collection("route");
Shared Directory
Apri src/shared folder and navigate to the makeResponse.ts 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.”
async function makeResponse(res: Response, action: () => Promise<any>) {
try {
const result = await action();
res.json(result);
} catch (e: any) {
console.error(e);
let status: number;
if (isCouchbaseError(e) && e.message.indexOf("not found") !== -1) {
status = 404;
} else {
status = isCouchbaseError(e) ? 400 : 500;
}
const errorResponse: ErrorResponse = { message: e.message };
res.status(status);
res.json(errorResponse);
}
}
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, and create a airport document using .insert() method. If the document is not found it is caught by the makeResponse method.
await makeResponse(res, async () => {
await airportCollection.insert(req.params.id, newairport);
res.status(201);
return newairport;
});
GET Airport
To fetch a airport document, locate the getAirport method within the airportController.ts 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 .get() metodo.
await makeResponse(res, async () => {
const getResult: GetResult = await airportCollection.get(req.params.id)
newairport = getResult['content']
return newairport
})
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.ts 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 () => {
await airportCollection.upsert(req.params.id, newairport);
return newairport;
});
Il updateAirport method chiama il .upsert() metodo.
DELETE Airport
To delete a airport document, locate the DeleteDocumentForAirport method within the airportController.ts 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 airportCollection.remove(req.params.id);
res.status(204);
return;
});
Delete Airport by Airport ID by using .remove() method 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++ è un linguaggio di query potente basato su SQL, ma progettato per documenti JSON strutturati e flessibili. Utilizzeremo una query SQL++ per cercare aeroporti con le opzioni Limit, Offset e Country.
Navigare fino alla listAirport il metodo nel airportController.ts 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.
Costruiamo la nostra query SQL++ utilizzando il named parameters specificato da $ simbolo per entrambi questi scenari. La differenza tra le due query è la presenza del paese Il parametro nella query. Normalmente, per le query con la funzione di paginaazione, si consiglia di ordinare i risultati per mantenere l'ordine dei risultati in più query.
Successivamente passiamo oltre richiesta e il parametri to the scope.query() method and return the results.
const country = (req.query.country as string) ?? "";
let limit = parseInt(req.query.limit as string, 10) || 10;
let offset = parseInt(req.query.offset as string, 10) || 0;
let query: string;
type QueryOptions = {
parameters: {
COUNTRY?: string;
LIMIT: number;
OFFSET: number;
};
};
let options: QueryOptions;
if (country !== "") {
query = `
SELECT airport.airportname,
airport.city,
airport.country,
airport.faa,
airport.geo,
airport.icao,
airport.tz
FROM airport AS airport
WHERE airport.country=$COUNTRY
ORDER BY airport.airportname
LIMIT $LIMIT
OFFSET $OFFSET;
`;
options = {
parameters: { COUNTRY: country, LIMIT: limit, OFFSET: offset },
};
} else {
query = `
SELECT airport.airportname,
airport.city,
airport.country,
airport.faa,
airport.geo,
airport.icao,
airport.tz
FROM airport AS airport
ORDER BY airport.airportname
LIMIT $LIMIT
OFFSET $OFFSET;
`;
options = { parameters: { LIMIT: limit, OFFSET: offset } };
}
await makeResponse(res, async () => {
let results: QueryResult = await scope.query(query, options);
return results["rows"];
});
Connessioni dirette
Questo endpoint recupera gli aeroporti raggiungibili direttamente dal codice aeroportuale di origine specificato. Utilizza anche una query SQL++ per recuperare i risultati, simile all’endpoint List Airport.
Consideriamo la query utilizzata qui:
SELECT DISTINCT route.destinationairport
FROM airport AS airport
JOIN route AS route ON route.sourceairport = airport.faa
WHERE airport.faa = $AIRPORT AND route.stops = 0
ORDER BY route.destinationairport
LIMIT $LIMIT
OFFSET $OFFSET
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.ts:
"scripts": {
"start": "npx env-cmd -f ./config/dev.env npx ts-node src/server.ts",
},
There are other scripts that we have added for our maintenance and testing of the project on GitHub using GitHub actions.
"scripts": {
"test": "env-cmd -f ./config/test.env jest --verbose --runInBand",
"testGA": "jest --verbose --runInBand"
},
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:
- Utilize the Interfaccia del server Couchbase to establish the new collection within the Couchbase bucket. Alternatively the collection can be created using the createCollection via the SDK.
-
Define the New Route:
- Navigare fino alla
src/routesfolder and create the new route.
- Navigare fino alla
-
Controller Configuration:
- Develop a new file in the
controllersfolder, mirroring the existing structures (e.g.,airportController.ts). Craft the corresponding method within this file to manage the new entity.
- Develop a new file in the
-
Add Tests:
- Aggiungere i test per le nuove rotte in un nuovo file nel
__test__folder similar to other collection tests.
- Aggiungere i test per le nuove rotte in un nuovo file nel
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.
- Seguimi Opzioni di installazione di Couchbase Per l'installazione dell'ultima istanza del server di database Couchbase.
È 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.