- Build a basic REST API using using Next.js and Couchbase Nodejs SDK
- See how you can fetch data from Couchbase without exposing API routes
- Explore CRUD operations in action with Couchbase
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.
-
Next.js 14 or higher installed
-
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.js SDK (4.x) for Couchbase. It will not work with older versions of Next.js without adapting the code.
-
Ensure that the Nodejs version is compatibile con il SDK di Couchbase.
-
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 Next.js 14. Please make sure you have Next.js 14 installed before proceeding.
Configurazione dell'applicazione
Cloning Repo
git clone https://github.com/couchbase-examples/nextjs-capella-quickstart.git
Installare le dipendenze
Any dependencies should be installed through the node package manager (npm). Navigate to the root directory and run the following command:
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.
Tutte le configurazioni per la comunicazione con il database vengono prelevate dalle variabili di ambiente. Abbiamo fornito una funzionalità di comodità in questo quickstart per leggere le variabili di ambiente da un file locale, .env nella cartella sorgente.
Creare una copia di .env.example apri il file e rinominalo in .env.local & aggiungi i valori per il cluster Couchbase.
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.
npm run dev
The application will start on port 3000 of your local machine (http://localhost:3000). The interactive Swagger documentation of the API can be found at http://localhost:3000/api-doc.
Usare 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
docker build -t nextjs-capella-quickstart . -f Dockerfile.dev
- Iniziare a eseguire l'immagine Docker
docker run -p 3000:3000 nextjs-capella-quickstart -e DB_CONN_STR=<connection_string> -e DB_USERNAME=<user_with_read_write_permission_to_travel-sample_bucket> -e DB_PASSWORD=<password_for_user>
Nota: Il
dev.envfile has the environment variables for the application. The-eflag is used to pass the environment variables to the container.
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). You will find the interactive Swagger documentation of the API if you go to the URL(http://localhost:3000/api-doc) in your browser. Swagger documentation is used in this demo to showcase the different API end points and how they can be invoked. More details on the Swagger documentation can be found in the 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
Dockerfile.dev
app
├── api
│ ├── hello
│ │ └── route.ts
│ └── v1
│ ├── airline
│ │ ├── [airlineId]
│ │ │ ├── route.test.ts
│ │ │ └── route.ts
│ │ ├── list
│ │ │ ├── route.test.ts
│ │ │ └── route.ts
│ │ └── to-airport
│ │ ├── route.test.ts
│ │ └── route.ts
│ ├── airport
│ │ ├── [airportId]
│ │ │ ├── route.test.ts
│ │ │ └── route.ts
│ │ └── direct-connections
│ │ ├── route.test.ts
│ │ └── route.ts
│ └── route
│ └── [routeId]
│ ├── route.test.ts
│ └── route.ts
├── api-doc
│ ├── page.tsx
│ └── react-swagger.tsx
├── layout.tsx
├── models
│ ├── Airline.ts
│ ├── Airport.ts
│ └── Route.ts
└── page.tsx
Connecting to Couchbase
We use the Couchbase Node.js SDK to connect to the Couchbase cluster. The connection is established in the couchbase-connection.ts file in the lib folder. The connection string and credentials are read from the environment variables.
Here is the code to connect to the Couchbase cluster:
interface DbConnection {
cluster: couchbase.Cluster;
bucket: couchbase.Bucket;
scope: couchbase.Scope;
airlineCollection: couchbase.Collection;
airportCollection: couchbase.Collection;
routeCollection: couchbase.Collection;
}
let cachedDbConnection: DbConnection | null = null;
declare const global: {
couchbase?: {
conn: couchbase.Cluster | null;
};
};
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached: { conn: couchbase.Cluster | null } = global.couchbase ?? {
conn: null,
};
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;
}
async function connectToDatabase(): Promise<DbConnection> {
const cluster = await createCouchbaseCluster();
const bucket = cluster.bucket(DB_BUCKET_NAME);
const scope = bucket.scope("inventory");
const airlineCollection = scope.collection("airline");
const airportCollection = scope.collection("airport");
const routeCollection = scope.collection("route");
const dbConnection: DbConnection = {
cluster,
bucket,
scope,
airlineCollection,
airportCollection,
routeCollection,
};
cachedDbConnection = dbConnection;
return dbConnection;
}
export function getDatabase(): Promise<DbConnection> {
if (!cachedDbConnection) {
// If connection doesn't exist, create and cache it
return connectToDatabase();
}
// If connection exists, return it
return Promise.resolve(cachedDbConnection);
}
Nel connectToDatabase function, we connect to the Couchbase cluster using the connection string and credentials. We then connect to the Travel-sample bucket and create references to the collections we will be using in the application.
Nel getDatabase function, we check if the connection exists and return it. If it doesn’t exist, we create and cache it.
We use the global object to maintain a cached connection across hot reloads in development. This prevents connections from growing exponentially during API route usage.
Entità aerea
Per questo tutorial ci concentreremo sull’entità dell’aerolinea. Le altre entità sono simili.
Stiamo creando un'API REST per gestire i documenti delle compagnie aeree.
- GET Airline – Leggere la compagnia aerea specificata
- POST Airline – Crea una nuova compagnia aerea
- PUT Airline – Aggiornamento della compagnia aerea specificata
- Elimina l'aerolino – Cancellare la compagnia aerea
- Elenco delle compagnie aeree – Raccogli tutte le compagnie aeree. Se desideri, puoi filtrare l'elenco per paese
Per le operazioni CRUD utilizzeremo il Operazioni chiave-valore che sono integrate nel Couchbase SDK per creare, leggere, aggiornare e cancellare un documento. Ogni documento avrà bisogno di un ID (simile a una chiave primaria in altre database) per essere salvato nel database. Questo ID viene passato nell'URL. Per gli altri endpoint, utilizzeremo SQL++ per richiedere documenti.
Struttura dei documenti dell'aerolinea
Il nostro documento di profilo conterrà il nome dell'aeroporto, la città, il paese, il codice FAA, il codice ICAO, le informazioni sulla zona oraria e le coordinate geografiche. Per questa demo, memorizzeremo tutte le informazioni sull'aeroporto in un unico documento nel aerolinea raccolta nel Travel-sample bucket.
{
"name": "40-Mile Air",
"iata": "Q5",
"icao": "MLA",
"callsign": "MILE-AIR",
"country": "United States"
}
GET Airline
Nel GET per raggiungere questo scopo, utilizziamo il ottenere method of the airlineCollection to fetch the document with the specified ID. If the document is not found, we return a 404 status code. If an error occurs, we return a 500 status code.
If the document is found, we return the document as a JSON response with a 200 status code.
export async function GET(
req: NextRequest,
{ params }: { params: { airlineId: string } }
) {
try {
const { airlineId } = params;
const { airlineCollection } = await getDatabase();
const airline = await airlineCollection.get(airlineId);
return NextResponse.json(airline.content as TAirline, { status: 200 });
} catch (error) {
if (error instanceof DocumentNotFoundError) {
return NextResponse.json(
{ message: "Airline not found", error: "Airline not found" },
{ status: 404 }
);
} else {
return NextResponse.json(
{
message: "An error occurred while fetching airline",
},
{ status: 500 }
);
}
}
}
POST Airline
Nel POST per raggiungere questo scopo, utilizziamo il inserire method of the airlineCollection to create a new document with the specified ID. If the document already exists, we return a 409 status code. If the request body is invalid, we return a 400 status code. If an error occurs, we return a 500 status code.
If the document is created successfully, we return the document as a JSON response with a 201 status code.
export async function POST(
req: NextRequest,
{ params }: { params: { airlineId: string } }
) {
try {
const { airlineId } = params;
const airlineData: TAirline = await req.json();
const parsedAirlineData = AirlineSchema.parse(airlineData);
const { airlineCollection } = await getDatabase();
const createdAirline = await airlineCollection.insert(
airlineId,
parsedAirlineData
);
return NextResponse.json(
{
airlineId: airlineId,
airlineData: parsedAirlineData,
createdAirline: createdAirline,
},
{
status: 201,
}
);
} catch (error) {
if (error instanceof DocumentExistsError) {
return NextResponse.json(
{
message: "Airline already exists",
error: "Airline already exists",
},
{ status: 409 }
);
} else if (error instanceof ZodError) {
return NextResponse.json(
{
message: "Invalid request body",
error: error.errors,
},
{ status: 400 }
);
} else {
return NextResponse.json(
{
message: "An error occurred while creating airline",
},
{ status: 500 }
);
}
}
}
PUT Airline
Nel PUT per raggiungere questo scopo, utilizziamo il upsert method of the airlineCollection to update the document with the specified ID. If the document does not exist, it is created. If the request body is invalid, we return a 400 status code. If an error occurs, we return a 500 status code.
If the document is updated successfully, we return the document as a JSON response with a 200 status code.
export async function PUT(
req: NextRequest,
{ params }: { params: { airlineId: string } }
) {
try {
const { airlineId } = params;
const airlineData: TAirline = await req.json();
const parsedAirlineData = AirlineSchema.parse(airlineData);
const { airlineCollection } = await getDatabase();
const updatedAirline = await airlineCollection.upsert(
airlineId,
parsedAirlineData
);
return NextResponse.json(
{
airlineId: airlineId,
airlineData: parsedAirlineData,
updatedAirline: updatedAirline,
},
{ status: 200 }
);
} catch (error) {
if (error instanceof ZodError) {
return NextResponse.json(
{ message: "Invalid request body", error: error.errors },
{ status: 400 }
);
} else {
return NextResponse.json(
{
message: "An error occurred while updating airline",
error: "An error occurred while updating airline",
},
{ status: 500 }
);
}
}
}
Elimina l'aerolino
Nel DELETE per raggiungere questo scopo, utilizziamo il rimuovere method of the airlineCollection to delete the document with the specified ID. If the document is not found, we return a 404 status code. If an error occurs, we return a 500 status code.
If the document is deleted successfully, we return a JSON response with a 202 status code.
export async function DELETE(
req: NextRequest,
{ params }: { params: { airlineId: string } }
) {
try {
const { airlineId } = params;
const { airlineCollection } = await getDatabase();
await airlineCollection.remove(airlineId);
return NextResponse.json(
{ message: "Successfully deleted airline" },
{ status: 202 }
);
} catch (error) {
if (error instanceof DocumentNotFoundError) {
return NextResponse.json(
{
message: "Airline not found",
error: "Airline not found",
},
{ status: 404 }
);
} else {
return NextResponse.json(
{
message: "An error occurred while deleting airline",
},
{ status: 500 }
);
}
}
}
List Airline
This endpoint retrieves the list of airlines in the database. The API has options to specify the page size for the results and country from which to fetch the airport documents.
Navigare fino alla GET il metodo nel app/api/v1/airline/list/route.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.
Innanzitutto, dobbiamo ottenere i valori dalla stringa di query per paese, limite e offset che utilizzeremo nella nostra query. Questi vengono recuperati tramite query parameters in Next.js API routes.
This endpoint has two queries depending on the value for the country parameter. If a country name is specified, we retrieve the airport documents for that specific country. If it is not specified, we retrieve the list of airlines across all countries. The queries are slightly different for these two scenarios.
Costruiamo la nostra query SQL++ utilizzando il parametri
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 alla classe CouchbaseClient richiesta metodo. Salviamo i risultati in una lista, airlines.
export async function GET(req: NextRequest) {
try {
const { scope } = await getDatabase();
const country = req.nextUrl.searchParams.get("country") ?? "";
const limit = req.nextUrl.searchParams.get("limit") ?? 10;
const offset = req.nextUrl.searchParams.get("offset") ?? 0;
let query: string;
type QueryOptions = {
parameters: {
COUNTRY?: string;
LIMIT: number;
OFFSET: number;
};
};
let options: QueryOptions;
if (country === "") {
query = `
SELECT air.callsign,
air.country,
air.iata,
air.icao,
air.id,
air.name,
air.type
FROM airline AS air
LIMIT $LIMIT OFFSET $OFFSET
`;
options = {
parameters: {
LIMIT: Number(limit),
OFFSET: Number(offset),
},
};
} else {
query = `
SELECT air.callsign,
air.country,
air.iata,
air.icao,
air.id,
air.name,
air.type
FROM airline AS air
WHERE air.country = $COUNTRY
LIMIT $LIMIT OFFSET $OFFSET
`;
options = {
parameters: {
COUNTRY: country,
LIMIT: Number(limit),
OFFSET: Number(offset),
},
};
}
const result: QueryResult = await scope.query(query, options);
const airlines: TAirline[] = result.rows;
return NextResponse.json(airlines, { status: 200 });
} catch (error) {
return NextResponse.json(
{
message: "An error occurred while fetching airlines",
},
{ status: 500 }
);
}
}
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 = $destinationAirportCode AND route.stops = 0
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.
Esecuzione dei test
Abbiamo definito i test di integrazione utilizzando Vite for all the API endpoints. The integration tests use the same database configuration as the application. For the tests, we perform the operation using the API and confirm the results by checking the documents in the database. For example, to check the creation of the document by the API, we would call the API to create the document and then read the same document directly from the database using the appropriate client and compare them. After the tests, the documents are cleaned up.
I test, compresi i dispositivi di fissaggio e gli ausili per i test, sono configurati nel file testi cartella.
Per eseguire i test, utilizzare il comando seguente:
npm install -g vitest
vitest app/api/v1/airline/[airlineId]/route.test.ts
Appendice
Ampliare l'API aggiungendo un'entità nuova
Se desiderate aggiungere un'altra entità alle API, i passaggi da seguire sono i seguenti:
- Creare la nuova entità (collezione) nel bucket Couchbase. È possibile creare la collezione utilizzando il comando SDK o tramite il Interfaccia del server Couchbase.
- Create the new entity model in the
modellifolder similar to the existing models likeAirline.ts. - Create the new API routes in the
api/v1una cartella simile alle rotte esistenti comeaerolinea.
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 nella cartella di origine.
Note: Couchbase Server must be installed and running prior to running the Nextjs 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.