In this tutorial, you will learn how to connect to a Couchbase Capella cluster to create, read, update, and delete documents and how to write simple parametrized SQL++ queries.

前提条件

To run this prebuilt project, you will need:

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.

Couchbase Capellaの設定

「couchbase」を以下のように実行すると、 Capella, 以下のような前提条件を満たしている必要があります。.

  • The application requires the travel-sample bucket to be loaded in the cluster from the Capella UI.
  • Create the データベース認証情報 アプリケーションで使用される travel-sample バケット (読み取りおよび書き込み) にアクセスします。.
  • アクセス許可を許可する アプリケーションが実行されている IP からのクラスタへの接続です。.

App Setup

Clone Repo

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

依存関係のインストール

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

npm install

データベース設定のセットアップ

Capella クラスターへの接続について詳しくは、こちらをご覧ください。 説明書.

具体的には、以下の手順を実行する必要があります:

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 での config folder.

Create a copy of 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=<connection_string>
DB_USERNAME=<user_with_read_write_permission_to_travel-sample_bucket>
DB_PASSWORD=<password_for_user>

Note: The connection string expects the couchbases:// または couchbase:// パート。.

アプリケーションの実行

Directly on Local Machine

At this point, we have installed the dependencies, loaded the travel-sample data and configured the application with the credentials. The application is now ready and you can run it.

The application will run on your local machine (http://localhost:3000). You will find the Swagger documentation of the API which you can use to try the API endpoints.

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

Docker

If you prefer to run this quick start using Docker, we have provided the Dockerfile which you can use to build the image and run the API as a container.

  • Build the Docker image
# Execute this command in the project's root directory
docker build -t couchbase-typescriptjs-quickstart .
  • Run the Docker image
# 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

Note: The config/dev.env file has the connection information to connect to your Capella cluster. With the --env-file, docker will inject those environment variables to the container.

Once the app is up and running, you can launch your browser and go to the Swagger documentation to test the APIs.

Verifying the Application

Once the application starts, you can see the details of the application on the logs.

Application Startup

The application will run on port 3000 of your local machine (http://localhost:3000). You will find the interactive Swagger documentation of the API if you go to the URL 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 appendix.

Swagger Documentation

データモデル

For this tutorial, we use three collections, airport, airline そして route that contain sample airports, airlines and airline routes respectively. The route collection connects the airports and airlines as seen in the figure below. We use these connections in the quickstart to generate airports that are directly connected and airlines connecting to a destination airport. Note that these are just examples to highlight how you can use SQL++ queries to join the collections.

img

Let Us Review the Code

To begin this tutorial, clone the repo and open it up in the IDE of your choice. Now you can learn about how to create, read, update and delete documents in Couchbase Server.

Code Layout

├── 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__ folder.

Airport Entity

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

We will be setting up a REST API to manage airport documents.

For CRUD operations, we will use the 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 airport collection in the 旅行サンプル 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
  }
}

Navigate to the connection.ts での 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 接続する メソッド。.

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

開く 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);
  }
}

POST Airport

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() メソッド。.

    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.

PUT Airport

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;
});

について updateAirport method calls the .upsert() メソッド。.

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.

List Airport

This endpoint retrieves the list of airports in the database. The API has options to specify the page size for the results and country from which to fetch the airport documents.

エスキューエルプラスプラス 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.

Navigate to the listAirport method in the airportController.ts file. This endpoint is different from the others we have seen before because it makes the SQL++ query rather than a key-value operation. This usually means more overhead because the query engine is involved. For this query, we are using the predefined indices in the 旅行サンプル bucket. We can create an additional インデックス specific for this query to make it perform better.

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 メソッド。.

This end point 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 airports across all countries. The queries are slightly different for these two scenarios.

We build our SQL++ query using the named parameters specified by $ symbol for both these scenarios. The difference between the two queries is the presence of the country parameter in the query. Normally for the queries with pagination, it is advised to order the results to maintain the order of results across multiple queries.

Next, we pass that クエリー そして parameters 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"];
});

Direct Connections

This endpoint fetches the airports that can be reached directly from the specified source airport code. This also uses a SQL++ query to fetch the results simlar to the List Airport endpoint.

Let us look at the query used here:

	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

We are fetching the direct connections by joining the airport collection with the route collection and filtering based on the source airport specified by the user and by routes with no stops.

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"
  },

Running Tests

We have defined integration tests using 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__ folder.

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

Appendix

Extending API by Adding New Entity

If you would like to add another entity to the APIs, these are the steps to follow:

  • Create the New Entity in Couchbase Bucket:

  • Define the New Route:

    • Navigate to the 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.ts). Craft the corresponding method within this file to manage the new entity.
  • Add Tests:

    • Add the tests for the new routes in a new file in the __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.

Running Self Managed Couchbase Cluster

If you are running this quickstart with a self managed Couchbase cluster, you need to load the travel-sample data bucket in your cluster and generate the credentials for the bucket.

You need to update the connection string and the credentials in the dev.env file in the config folder.

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

Swagger Documentation

Swagger documentation provides a clear view of the API including endpoints, HTTP methods, request parameters, and response objects.

Click on an individual endpoint to expand it and see detailed information. This includes the endpoint’s description, possible response status codes, and the request parameters it accepts.

Trying Out the API

You can try out an API by clicking on the “Try it out” button next to the endpoints.

  • Parameters: If an endpoint requires parameters, Swagger UI provides input boxes for you to fill in. This could include path parameters, query strings, headers, or the body of a POST/PUT request.

  • Execution: Once you’ve inputted all the necessary parameters, you can click the “Execute” button to make a live API call. Swagger UI will send the request to the API and display the response directly in the documentation. This includes the response code, response headers, and response body.

モデル

Swagger documents the structure of request and response bodies using models. These models define the expected data structure using JSON schema and are extremely helpful in understanding what data to send and expect.

データベースの膨大なサイズを過去のものとしておく

スタックの追加ごとに新たな請求書が発生し、管理するものがさらに増えます。2分でどれだけの節約ができるかを試算してください。.