node.js rest
If you are building an application using Node.js, it can get a little overwhelming since there are a variety of databases to choose from and different ways to build APIs. One way to reduce development time and focus on the problem you are trying to solve is to use Database as a service to store the data. The advantage of this approach is to use a cloud database system without purchasing hardware which can be cost and time effective.
如果您使用Node.js构建应用程序,则可能会有些不知所措,因为有多种数据库可供选择,并且构建API的方法也不同。 减少开发时间并专注于要解决的问题的一种方法是将数据库作为服务来存储数据。 这种方法的优点是无需购买硬件即可使用云数据库系统,这可以节省成本和时间。
One such database service is HarperDB Cloud. To build REST APIs rapidly this service allows us to perform all database operations using a single endpoint. It supports a variety of programming languages such as JavaScript, Java, Python, and so on. Some of the features of HarperDB are the following:
HarperDB Cloud就是这样一种数据库服务。 为了快速构建REST API,该服务使我们可以使用单个端点执行所有数据库操作。 它支持多种编程语言,例如JavaScript,Java,Python等。 HarperDB的一些功能如下:
- single endpoint API单端点API
- allow JSON, CSVs file insertions允许插入JSON,CSV文件
- support SQL queries for full CRUD operations支持SQL查询以进行完整的CRUD操作
- Supports Math.js and GeoJSON支持Math.js和GeoJSON
- limited database configuration required需要有限的数据库配置
In this post, let’s build a simple REST API using Node.js and HarperDB Cloud to store some data. We are also going to use Express as the framework to build the Node.js server. It is a minimal and quite unopinionated framework.
在本文中,让我们使用Node.js和HarperDB Cloud构建一个简单的REST API,以存储一些数据。 我们还将使用Express作为构建Node.js服务器的框架。 这是一个小且完全不受质疑的框架。
先决条件 (Prerequisites)
Before you begin this tutorial, you’re going to need the following:
在开始本教程之前,您需要满足以下条件:
Node.js version above
12.x.x
installed on your local machine您本地计算机上安装的Node.js版本高于
12.xx
- Access to a package manager such as npm or yarn访问软件包管理器,例如npm或yarn
- Basic JavaScript and ES6 knowledge基本JavaScript和ES6知识
Access to a HarperDB Cloud instance (free tier)
访问HarperDB Cloud实例( 免费 )
To continue with the rest of the tutorial, please make sure you have an account with HarperDB Cloud and are logged in.
要继续学习本教程的其余部分,请确保您已经拥有HarperDB Cloud帐户并已登录。
入门 (Getting started)
Start by creating the project directory on a local development environment. Give this directory a name and navigate into it. Then, initialize this project to manage npm dependencies by creating a package.json
file.
首先在本地开发环境上创建项目目录。 为该目录命名并导航至该目录。 然后,通过创建package.json
文件初始化此项目以管理npm依赖项。
The --yes
flag uses the default settings when initializing a package.json
from npm config you might have set up.
从可能已设置的npm config初始化package.json
时,-- --yes
标志使用默认设置。
After the initializing step, let us add an express package. From the terminal window, run the command:
初始化步骤之后,让我们添加一个快递包裹。 在终端窗口中,运行以下命令:
Next, create a new file called index.js
at the root of the project with the following code to trigger a minimal server:
接下来,使用以下代码在项目的根目录创建一个名为index.js
的新文件,以触发小服务器:
In the above code snippet, the app
is an object provided by Express API for the developer to communicate with the application and bootstrap a server.
在上面的代码片段中, app
是Express API提供的对象,供开发人员与应用程序通信并引导服务器。
Go back to the terminal and trigger the common node index.js
to start the server. This node
command is the simplest way to trigger a development server when building APIs with Node.js. Now, open up your favorite REST client to test APIs. For the demonstration purpose, I am going to use Insomnia.
返回终端并触发公共node index.js
以启动服务器。 使用Node.js构建API时,此node
命令是触发开发服务器的简单方法。 现在,打开您喜欢的REST客户端以测试API。 出于演示目的,我将使用Insomnia 。
You can test API endpoint by invoking a call to http://localhost:8000
and it is going to return the result as shown below.
您可以通过调用http://localhost:8000
来测试API终结点,它将返回结果
使用nodemon监视文件更改 (Watching file changes with nodemon)
An essential development-related utility library that saves time when working on Node.js projects is nodemon. It’s a tool that helps the development of Node.js based applications by automatically restarting the Node application when file changes in the directory are detected.
nodemon是一个与开发相关的,必不可少的实用程序库,它可以节省处理Node.js项目的时间 。 它是通过在检测到目录中的文件更改时自动重新启动Node应用程序来帮助开发基于Node.js的应用程序的工具。
To start using it in the current Express server, install it by using yarn add -D nodemon
where -D
flag is used to indicate that the dependency to install is a devDependency
. After installing this dev dependency, open package.json
file and add a start script as shown below.
要在当前Express服务器中开始使用它,请使用yarn add -D nodemon
进行安装,其中-D
标志用于指示要安装的依赖项是devDependency
。 安装此开发依赖项后,打开package.json
文件并添加一个启动脚本,如下所示。
Now, you can use either npm run start
or yarn run start
command to trigger the server. That's it to set up a basic Node.js server using the Express framework.
现在,您可以使用npm run start
或yarn run start
命令来触发服务器。 就是使用Express框架设置基本的Node.js服务器。
设置HarperDB Cloud实例 (Setting up an instance of HarperDB Cloud)
In the introductory section of this post, you get the idea of what HarperDB Cloud is and features it supports. In this section, let us create the first database instance to store the data for the REST API using this cloud database service.
在本文的简介部分,您将了解HarperDB Cloud是什么及其支持的功能。 在本节中,让我们创建个数据库实例,以使用该云数据库服务存储REST API的数据。
Assuming by now you have access main dashboard screen as shown below. To create a new instance, click on the plus button.
假设现在您可以访问仪表板主屏幕,如下所示。 要创建一个新实例,请单击加号按钮。
Then select the HarperDB Cloud instance option.
然后选择HarperDB Cloud实例选项。
Fill in the details regarding the instance. Make sure to create a strong password and give a better username under Instance Credentials (I am keeping them simple for brevity).
填写有关实例的详细信息。 确保创建一个强密码,并在“实例凭据”下提供更好的用户名(为简洁起见,我将其简化)。
If you are on the free tier, leave everything in the screen below to default selections and click the button Confirm Instance Details
.
如果您使用的是免费套餐,则将以下屏幕中的所有内容保留为默认选择,然后单击Confirm Instance Details
按钮。
After entering the details, it is going to ask you to re-confirm all the instance details you have entered and if everything is okay, press the button Add Instance
.
输入详细信息后,将要求您重新确认输入的所有实例详细信息,如果一切正常,请按Add Instance
按钮。
Make sure to remember the username and the password you have entered here. They will be required to authenticate the Node.js server with the HarperDB Client. Once the instance of the cloud database is created, it is going to appear as shown below.
确保记住您在此处输入的用户名和密码。 他们将需要使用HarperDB Client对Node.js服务器进行身份验证。 创建云数据库的实例后,它将如下所示。
You can click on the instance card from the UI and will be welcomed by the first screen to add a schema.
您可以从用户界面中单击实例卡,个屏幕将欢迎您添加一个架构。
A schema in HarperDB is necessary. It is equivalent to a collection of tables. Without an existing schema, you cannot create a new table and without a table, you cannot add or update data from HarperDB instance. To proceed, the schema and the table has to be created. Let’s do it with the UI interface.
HarperDB中的架构是必需的。 它等效于表的集合。 没有现有模式,就不能创建新表,没有表,就不能从HarperDB实例添加或更新数据。 要继续,必须创建模式和表。 让我们用UI界面来做。
On the left-hand side, under the header where it says schemas
, write in the name of your first schema.
在左侧,在标题为schemas
的标题下,输入个模式的名称。
Once a schema is created, the option to add one or more tables appears. Let’s create the first table called books
as shown below. Besides the name of the table, HarperDB also asks to enter or assign the field for a hash_attribute
. This attribute is equivalent to the unique identifier for each record that exists in the table books
. Traditionally, most data tables have id
as the unique identifier so it is passed as the value.
创建架构后,将显示添加一个或多个表的选项。 让我们创建个表,即books
,如下所示。 除了表的名称,HarperDB还要求进入或分配领域的hash_attribute
。 此属性等效于表books
中存在的每个记录的标识符。 传统上,大多数数据表都将id
作为标识符,因此将其作为值传递。
The schema as well as the table are now successfully created.
现在已成功创建模式和表。
Let’s save all the credentials required for the Node.js server to connect to the database. Create a .env
file at the root of the project with for keys as shown below.
让我们保存Node.js服务器连接到数据库所需的所有凭据。 在项目的根目录下使用for键创建一个.env
文件,如下所示。
You are going to add your own HarperDB instance values here. Do not use the same values for each key as shown above, since it won’t work. This just to demonstrate that these values are not wrapped inside quotes.
您将在此处添加自己的HarperDB实例值。 如上所示,请勿对每个键使用相同的值,因为它将无法正常工作。 这只是为了证明这些值未包含在引号中。
将HarperDB Cloud与Nodejs服务器连接 (Connecting HarperDB Cloud with a Nodejs server)
To connect the HarperDB Cloud instance created in the previous section, let’s install a dependency called Harperive that is going to let us interact with the database by performing CRUD (Create, Read, Update, Delete) operations. Go back to the terminal window and run the command:
为了连接在上一节中创建的HarperDB Cloud实例,让我们安装一个称为Harperive的依赖关系,该依赖关系将通过执行CRUD( 创建,读取,更新,删除 )操作与数据库进行交互。 返回终端窗口并运行命令:
Once the dependency is installed, create a new directory called config and inside it, create a new file called dbconfig.js
.
安装依赖项后,创建一个名为config的新目录,并在其中创建一个名为dbconfig.js
的新文件。
To connect to the database instance, you require three things:
要连接到数据库实例,您需要做三件事:
- Database instance URL数据库实例URL
- Database instance username数据库实例用户名
- Database instance password数据库实例密码
At the end of the previous section, all these values are saved inside a .env
file as environment variables. Using the dotenv
package, these environment variables are now accessible throughout the Node.js server app. Inside the dbconfig.js
file, import dotenv
package as the first line and then import harperive
. Create a DB_CONFIG
object that is going to be passed as the argument to harperive.client
. The schema
field in the DB_CONFIG
object is optional. Since this demo app has only one schema, thus, to avoid mentioning the schema field again and again when sending a query to the database, its name can be passed here.
在上一节的末尾,所有这些值都作为环境变量保存在.env
文件中。 使用dotenv
包,现在可以在整个Node.js服务器应用程序中访问这些环境变量。 里面的dbconfig.js
文件,导入dotenv
包作为行,然后导入harperive
。 创建一个DB_CONFIG
对象,该对象将作为参数传递给harperive.client
。 DB_CONFIG
对象中的schema
字段是可选的。 由于此演示应用程序只有一个架构,因此,为了避免在向数据库发送查询时一再提及架构字段,可以在此处传递其名称。
Add the following code snippet to the dbconfig.js
file.
将以下代码片段添加到dbconfig.js
文件。
Exporting the db
instance of the actual HarperDB client is going to allow us to query the database.
导出实际HarperDB客户端的db
实例将允许我们查询数据库。
设置人体解析器 (Setting up body-parser)
To set up routes or endpoints of the server application, you need to include body-parser
in the index.js
.
要设置服务器应用程序的路由或端点,您需要在index.js
包括body-parser
。
BodyParser parses incoming HTTP requests as middleware under req.body
before routes or API have access to them and perform any further actions on them. A very useful and essential step when using forms in a web application.
在路由或API可以访问传入的HTTP请求req.body
它们执行任何进一步的操作之前,BodyParser会将传入的HTTP请求解析为req.body
下的中间件。 在Web应用程序中使用表单时,这是非常有用且必不可少的步骤。
The urlencoded
method in the above snippet allows the body-parser middleware to extract data from form fields. In the REST client such as Postman or Insomnia, it is possible to send the data as form fields. The json
method allows the JSON data to be extracted.
以上代码段中的urlencoded
方法允许主体分析器中间件从表单字段提取数据。 在诸如Postman或Insomnia之类的REST客户端中,可以将数据作为表单字段发送。 json
方法允许提取JSON数据。
查询以添加新记录 (Query to add a new record)
Since the database doesn’t have any records, let’s start by writing the first query to insert new data in the database. Create a new directory called api/
and inside it create a new file called index.js
. Open index.js file and import the db
from config/dbconfig.js
file.
由于数据库没有任何记录,因此让我们首先编写个查询以在数据库中插入新数据。 创建一个名为api/
的新目录,并在其中创建一个名为index.js
的新文件。 打开index.js文件,然后从config/dbconfig.js
文件导入db
。
One of the main advantages of HarperDB is in querying the data from a database instance. It allows us to query the data either in the form of SQL queries or NoSQL queries. The advantage here is that the power of complex SQL queries can easily be used here to perform an operation. I am going to define all the queries in NoSQL form, however, do not forget to check official docs for more information on performing SQL queries here.
HarperDB的主要优点之一是从数据库实例中查询数据。 它允许我们以SQL查询或NoSQL查询的形式查询数据。 这样做的好处是,可以在此处轻松地使用复杂SQL查询的功能来执行操作。 我将以NoSQL形式定义所有查询,但是,不要忘记在此处查看官方文档以获取有关执行SQL查询的更多信息。
The first query is going to be called addBook
. This query is going to insert the data incoming from an HTTP request.
个查询将称为addBook
。 该查询将插入从HTTP请求传入的数据。
Each of the query functions as in the above code snippet is going to have at least two parameters: request
and response
.
上面的代码片段中的每个查询功能都将至少具有两个参数: request
和response
。
request
: useful when creating or updating a new task and read data from the body (this where BodyParser works like a charm).request
:在创建或更新新任务以及从正文中读取数据时很有用(BodyParser在此就像一个超级按钮一样工作)。response
: useful to fulfill that incoming request with a response from the server. Generally, it contains the correct status code of the HTTP status code. This HTTP status code determines whether the incoming request was fulfilled or if there is an error. This the part of the REST paradigm and is considered a best practice.response
:有用服务器的响应来满足该传入请求。 通常,它包含HTTP状态代码的正确状态代码。 此HTTP状态代码确定传入的请求是否已满足或是否有错误。 这是REST范式的一部分,被认为是佳实践。
When inserting data using a NoSQL query, it is mandatory to specify the name of the table in the database. In the current case its books
. Since you have already specified the Schema when creating a connection using the HarperDB client, there is no need to explicitly define it here. records
in HarperDB are similar to rows of data with having each field as a column.
使用NoSQL查询插入数据时,必须在数据库中指定表的名称。 在目前的情况下它的books
。 由于使用HarperDB客户端创建连接时已经指定了Schema,因此无需在此处显式定义它。 HarperDB中的records
类似于数据行,每个字段都作为一列。
You may have noticed in the above query that I am not explicitly adding an id
attribute to uniquely identify each data record. HarperDB automatically creates a unique id
for each data record.
您可能已经在上面的查询中注意到,我没有显式添加id
属性来标识每个数据记录。 HarperDB自动为每个数据记录创建一个的id
。
The data being inserted here has two fields. The title
and the author
for each book. They represent the name of the columns or attributes in each data record. The value of each of these fields is going to be the incoming value from an HTTP request, parsed by the body-parser
middleware function.
此处插入的数据有两个字段。 每本书的title
和author
。 它们代表每个数据记录中的列名或属性。 这些字段中的每个字段的值都将是来自HTTP请求的传入值,该请求由body-parser
中间件功能解析。
运行个查询以插入数据 (Running the first query to insert data)
To insert the first data record in the database lets create a route. Open index.js
file in the root directory and import the api
as routesController
. A controller is a naming convention in an Express framework app. It is the business logic that binds the endpoints/routes that are going to define below to what action or operation they will perform on an incoming request on that particular route.
要将条数据记录插入数据库中,请创建一条路由。 在根目录中打开index.js
文件,然后将api
作为routesController
导入。 控制器是Express框架应用程序中的命名约定。 业务逻辑将下面要定义的端点/路由绑定到它们将对该特定路由的传入请求执行的操作或操作。
Go back to the REST client and make sure the Node.js server is running from the terminal window.
返回REST客户端,并确保Node.js服务器正在从终端窗口运行。
Add the endpoint which is http://localhost:8000/books
, select the type of the request which is POST
. Select option Form URL encoded
and the two key-value pairs as shown below:
添加端点http://localhost:8000/books
,选择请求的类型POST
。 选择选项“ Form URL encoded
和两个键值对,如下所示:
Press the Send
button it an HTTP request to insert the data to the HarperDB is made. If it's successful, a success message shown below is returned.
按下Send
按钮,它发出一个HTTP请求,将数据插入到HarperDB中。 如果成功,则返回如下所示的成功消息。
Go back to the HarperDB studio and you are going to see the same data record being shown.
回到HarperDB工作室,您将看到相同的数据记录。
Do notice the two timestamp fields. They are auto inserted by the HarperDB and are auto-maintained.
请注意两个时间戳字段。 它们由HarperDB自动插入并自动维护。
__createdtime__
: to record the timestamp when data is inserted.__createdtime__
:记录插入数据时的时间戳。__updatedtime__
: to record the timestamp when any data field is updated for the last time.__updatedtime__
:记录后一次更新任何数据字段时的时间戳。
Try to add more values to the database.
尝试将更多的值添加到数据库。
查询按值搜索 (Query to search by value)
HarperDB allows to search database records in a table by using a column field name which is also known as an attribute
. Let's add another query to get a data record when an HTTP request is sent just by searching the name of the author. Open api/index.js
file and the following:
HarperDB允许使用列字段名(也称为attribute
搜索表中的数据库记录。 让我们添加另一个查询以仅通过搜索作者的姓名来发送HTTP请求时获取数据记录。 打开api/index.js
文件以及以下内容:
The data returned from the database is going to be in JSON format. Go back to the main index.js
file and add another route.
从数据库返回的数据将采用JSON格式。 返回主index.js
文件,并添加另一条路由。
Open the REST Client and make a request as shown below. The response of this HTTP request is going to be every data record that contains the value of the attribute author
.
打开REST Client并发出如下所示的请求。 该HTTP请求的响应将是包含属性author
值的每个数据记录。
查询以哈希搜索 (Query to search by hash)
Another important way to search for data in a table is by the unique identifier. HarperDB has a special method to do the same. This method is called searchByHash
and only allows us to search the database table using the identifier specified as has an attribute. In the api/index.js
file, add another query called getById
.
在表中搜索数据的另一种重要方式是通过标识符。 HarperDB有一种特殊的方法可以做到这一点。 此方法称为searchByHash
,仅允许我们使用指定为具有属性的标识符来搜索数据库表。 在api/index.js
文件中,添加另一个名为getById
查询。
When this query successfully runs, the result from the database is only going to show the title
attribute of the data record. This is done by passing the name of an attribute as the value of the attributes
property in the above snippet.
成功运行此查询后,数据库的结果将仅显示数据记录的title
属性。 这是通过在上面的代码段中将attributes
名称作为attributes属性的值来传递的。
Add the endpoint in the main index.js
file.
将端点添加到主index.js
文件中。
Go to the REST client and run the query.
转到REST客户端并运行查询。
查询删除数据记录 (Query to delete the data record)
To delete a record from the table in HarperDB is simple. All you have to do is pass the id
or the unique identifier for the record stored in the table. The unique identifier, as you know, is stored as a hash value.
从HarperDB中的表中删除记录很简单。 您所需要做的就是传递表中存储的记录的id
或标识符。 如您所知,标识符存储为哈希值。
Add the following query to the api/index.js
file.
将以下查询添加到api/index.js
文件。
Next, go to the main index.js
file and add the endpoint.
接下来,转到主index.js
文件并添加端点。
Lastly, go back to the REST client, pass on the id of the data record to delete. On successful deletion, it gives a response back in the form of a message
that is directly sent from the HarperDB instance. This is very helpful since this message response can be directly used with any REST client or sent to a frontend framework.
后,返回REST客户端,传递要删除的数据记录的ID。 成功删除后,它将以直接从HarperDB实例发送的message
形式返回响应。 这非常有用,因为此消息响应可以直接与任何REST客户端一起使用或发送到前端框架。
结论 (Conclusion)
Congratulations! You have reached the end of the tutorial.
恭喜你! 您已经到了本教程的结尾。
I hope this post does convey you to try the capabilities of HarperDB. I personally like how it support both SQL and NoSQL queries as well as some advanced features like adding timestamps automatically and hashing unique ids in a consistent way across all data tables and schemas.
我希望这篇文章能传达您尝试HarperDB的功能。 我个人喜欢它如何同时支持SQL和NoSQL查询以及一些功能,例如自动在所有数据表和架构中以一致的方式自动添加时间戳和哈希ID。
For updates on new posts and tutorials written by me, you can sign up my bi-weekly newsletter here.