Creating New APIs and Views in JHipster – 在JHipster中创建新的API和视图

最后修改: 2019年 3月 31日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

In this tutorial, we’ll see how we can create a new API inside a JHipster application. We’ll then integrate that API into the front-end display.

在本教程中,我们将看到如何在JHipster应用程序内创建一个新的API。然后,我们将把该API集成到前端显示中。

2. Sample Application

2.申请书样本

For this tutorial, we’ll be using a simple book store application.

在本教程中,我们将使用一个简单的图书商店应用程序。

The book store is built as a monolith. It uses Angular for the front-end and has a single entity named book with the following fields:

书店是作为一个单体建立的。它在前端使用Angular,并有一个名为book的单一实体,具有以下字段。

  • Title
  • Author
  • Published Data
  • Price
  • Quantity

JHipster automatically generates APIs and front-end views that provide simple operations for a book: view, create, edit, and delete.

JHipster自动生成API和前端视图,为一本书提供简单的操作:查看、创建、编辑和删除。

For this tutorial, we’ll add an API that lets a user purchase a book, along with a button on the front-end that calls the new API.

在本教程中,我们将添加一个让用户购买图书的API,同时在前端添加一个调用新API的按钮。

We’ll focus just on the API and front-end aspects of purchasing. We won’t perform any payment processing and only minimal validation.

我们将只专注于API和购买的前端方面。我们不会进行任何支付处理,只进行最小的验证。

3. Spring Boot Changes

3.Spring Boot的变化

JHipster provides a generator for creating new controllers. However, for this tutorial, we’ll manually create the API and associated code.

JHipster提供了一个生成器,用于创建新的controllers。然而,在本教程中,我们将手动创建API和相关代码

3.1. Resource Class

3.1.资源类

The first step is to update the generated BookResource class. We add the new endpoint that the front-end code will call:

第一步是更新生成的BookResource类。我们添加前端代码将调用的新端点

@GetMapping("/books/purchase/{id}")
public ResponseEntity<BookDTO> purchase(@PathVariable Long id) {
    Optional<BookDTO> bookDTO = bookService.purchase(id);
    return ResponseUtil.wrapOrNotFound(bookDTO);
}

This creates a new API endpoint located at /books/purchase/{id}. The only input is the book’s id, and we return a BookDTO that will reflect the new stock level after purchasing.

这将创建一个新的API端点,位于/books/purchase/{id}。唯一的输入是书的id,我们返回一个BookDTO,它将反映购买后的新库存水平。

3.2. Service Interface and Class

3.2.服务接口和类

Now, we need to update the BookService interface to include a new purchase method:

现在,我们需要更新BookService接口,以包括一个新的purchase方法:

Optional<BookDTO> purchase(Long id);

Then, we need to implement the new method in the BookServiceImpl class:

然后,我们需要在BookServiceImpl类中实现这个新方法。

@Override
public Optional<BookDTO> purchase(Long id) {
    Optional<BookDTO> bookDTO = findOne(id);
    if (bookDTO.isPresent()) {
        int quantity = bookDTO.get().getQuantity();
        if (quantity > 0) {
            bookDTO.get().setQuantity(quantity - 1);
            Book book = bookMapper.toEntity(bookDTO.get());
            book = bookRepository.save(book);
            return bookDTO;
        }
        else {
            throw new BadRequestAlertException("Book is not in stock", "book", "notinstock");
        }
    }
    return Optional.empty();
}

Let’s look at what is happening in this code. First, we look up the book by its id to confirm it exists. If it doesn’t, we return an empty Optional.

让我们看看这段代码中发生了什么。首先,我们通过书的id来确认它的存在。如果不存在,我们返回一个空的Optional

If it does exist, then we ensure it has a stock level greater than zero. Otherwise, we throw a BadRequestAlertException. While this exception is normally only used in the REST layer of JHipster, we’re using it here to demonstrate how to return useful error messages to the front-end.

如果它确实存在,那么我们确保它的库存水平大于零。否则,我们抛出一个BadRequestAlertException。虽然这个异常通常只在JHipster的REST层使用,但我们在这里使用它来演示如何向前端返回有用的错误信息。

Otherwise, if the stock is greater than zero, then we reduce it by one, save it to the repository, and return the updated DTO.

否则,如果存量大于零,那么我们将其减少1,保存到存储库,并返回更新的DTO。

3.3. Security Configuration

3.3.安全配置

The final change required is in the SecurityConfiguration class:

最后需要修改的是SecurityConfiguration类。

.antMatchers("/api/books/purchase/**").authenticated()

This ensures calls to our new API are only allowed by authenticated users.

这可以确保只有经过认证的用户才可以调用我们的新API。

4. Front-End Changes

4.前端变化

Now let’s focus on the front-end changes. JHipster creates a view for displaying a single book, and that’s where we’ll add our new purchase button.

现在让我们关注一下前端的变化。JHipster创建了一个用于显示单一书籍的视图,这就是我们要添加新的购买按钮的地方

4.1. Service Class

4.1.服务类别

First, we need to add a new method to the existing book.service.ts file. This file already contains the methods for manipulating book objects, so it’s a good place to add the logic for our new API:

首先,我们需要在现有的book.service.ts文件中添加一个新的方法。这个文件已经包含了操作图书对象的方法,所以它是一个为我们的新API添加逻辑的好地方。

purchase(id: number): Observable<EntityResponseType> {
    return this.http
        .get<IBook>(`${this.resourceUrl}/purchase/${id}`, { observe: 'response' })
        .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}

4.2. Component

4.2.组成部分

Then, we need to update the component code in book.component.ts. We’ll create a function that calls the new method in the Angular book service and then listens for the response back from the server:

然后,我们需要更新book.component.ts中的组件代码。我们将创建一个函数,调用Angular图书服务中的新方法,然后监听从服务器返回的响应。

purchase(id: number) {
    this.bookService.purchase(id).subscribe(
        (res: HttpResponse<IBook>) => {
            this.book = res.body;
        },
        (res: HttpErrorResponse) => console.log(res.message)
    );
}

4.3. View

4.3. 查看

Finally, we can add a button to the book view that calls the new purchase method in the component:

最后,我们可以在图书视图中添加一个按钮,调用组件中的新购买方法。

<button type="button"
             class="btn btn-primary"
             (click)="purchase(book.id)">
    <span>Purchase</span>
</button>

The image below shows the updated view on the front-end:

下面的图片显示了前端的更新视图。

jhipster custom api frontend

Clicking the new Purchase button will result in a call to our new API, and the front-end will automatically update with the new stock status (or display an error if something went wrong).

点击新的购买按钮将导致对我们新的API的调用,前端将自动更新新的库存状态(如果出错,则显示一个错误)。

5. Conclusion

5.总结

In this tutorial, we have seen how to create custom APIs in JHipster, and integrate them into the front-end.

在本教程中,我们已经看到了如何在JHipster中创建自定义API,并将其集成到前端。

We started by adding the API and business logic into Spring Boot. Then, we modified the front-end code to utilize the new API and display the results. With just a little effort we were able to add new functionality on top of the existing CRUD operations that JHipster automatically generates.

我们首先将API和业务逻辑添加到Spring Boot中。然后,我们修改了前端代码以利用新的API并显示结果。只需一点点努力,我们就能在JHipster自动生成的现有CRUD操作之上添加新的功能。

And as always, the code is available over on GitHub.

一如既往,代码可在GitHub上获得。