Spring REST TypeScript master builder

You Rui share in java class in a discussion about Spring REST TypeScript generator, the generator creates model and reflect the back-end service model and REST services. Code a lot of dry goods share to reference study.

I noticed that Web developers create a TypeScript models and services to reflect our back-end models and REST services. This is a tedious task. More importantly, after they finally reflect our back-end functionality, this is not the end. Because we always have to keep in mind in software development very common thing ... change. As the number of new business requirements, modify the back-end services. The change forced the front-end developers to re-analyze the back-end services and reconstruction of front-end applications, so that they match the server side.

After some time, I started a Web development adventure, and proposed the idea based on the type of information can generate all these in Java code. I started looking for a TypeScript generator, the generator will be able to create models and services in TypeScript REST-based interface. As my research shows, there are already some libraries provide this functionality, but they can not meet all our needs, for example:

  • Support JavaBean conventions.
  • Support FasterXML / Jackson comments.
  • To support Spring Framework - Generate TypeScript service, you can call the development in Spring REST API.
  • Generated services meet the specific requirements of Angular and ReactJS (Observable or Promises API).

Therefore, we decided to start a small off-hours project, which will provide the above functions. It can work, we propose a solution for immediate use. It has been based on our most tested and use Angular or React Web applications in commercial projects.

As our experience shows, our library has brought great benefits. The average generated code accounted for 20% Web application code base, but saving changes and test work is concerned, it is priceless. Because made such encouraging results, our company decided to open source projects. If your development using the Spring framework set up in the back end, or use Angular React at the front, then you will get the same benefits with us. In this short article, I would like to introduce how to use our spring-rest-2-ts TypeScript generator be REST.

example

In order to understand the spring-rest2ts generator function, let's create a simple REST model and controller in Java, we will show the content generated in TypeScript

 1 public class BaseDTO {
 2 
 3     private int id;
 4 
 5     @JsonFormat(shape = JsonFormat.Shape.NUMBER)
 6 
 7     private Date updateTimeStamp;
 8 
 9  }
10 
11 public class OrderDTO extends BaseDTO {
12 
13     private double price;
14 
15     @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
16 
17     private LocalDateTime orderTimestamp;
18 
19 }
20 
21  

 

Spring REST Controller:

 1 @Controller
 2 
 3 @RequestMapping("api/order")
 4 
 5 public class OrderCtrl {
 6 
 7     @PostMapping(consumes = {"application/json"}, produces = {"application/json"})
 8 
 9     @ResponseBody
10 
11     @ResponseStatus(HttpStatus.CREATED)
12 
13     public OrderDTO createOrder(@RequestBody OrderDTO entity) {
14 
15         return entity;
16 
17     }
18 
19     @RequestMapping(path = "/{id}", method = RequestMethod.GET, produces = {"application/json"})
20 
21     @ResponseBody
22 
23     public OrderDTO getOrder(@PathVariable int id) {
24 
25         return new OrderDTO();
26 
27     }
28 
29 }
30 
31  

 

In TypeScript, for DTO class, we obtain two interfaces having inherited mappings, wherein each field are mapped to respective TypeScript type:

 1 export interface Base {
 2 
 3     id: number;
 4 
 5     updateTimeStamp: number;
 6 
 7 }
 8 
 9 export interface Order extends Base {
10 
11     price: number;
12 
13     /**
14 
15      *    pattern : dd-MM-yyyy hh:mm:ss
16 
17      */
18 
19     orderTimestamp: string;
20 
21 }

 

 

As we have seen, if the field has Jackson comment, it will be taken into account. If not, then convert it to map a Java-based type of TypeScript. Support type name mapping. In Java, we see OrderDTO by providing an appropriate name mapper, the map will cut off the suffix DTO, and then we get Order Types

Observable basic services

Model class maps are very easy to understand. Even more interesting is mapped Spring REST controller, in TypeScript, the map has been generated for implementing call endpoint. This method is hidden under the method name, and path parameters, so that code can change the resistance of the rear end. More importantly, we will convert the return type for the selected Web framework. For Angular 2+, there is generated a valid Angular services available for injection:

 1 @Injectable()
 2 
 3 export class OrderService {
 4 
 5     httpService: HttpClient;
 6 
 7     public constructor(httpService: HttpClient) {
 8 
 9         this.httpService = httpService;
10 
11     }

 

As OrderCtrl generated OrderService. Here, the type name type name is also converted by the mapper. If the REST API and the Web application is not on the same host, you can configure baseURL, it can be a path prefix whole host of references

Based on pledges

For Web Promise API frame generator, the correct configuration can also generate service class:

1 export class OrderService {
 2  
3      baseURL: URL;
4  
5      public constructor (baseURL: URL = new URL (window.document.URL)) {
 6  
7          this .baseURL = baseURL;
8  
9      }
 10  
11      public createOrder (entity: Order): Promise <Order> {
 12  
13          int url = new URL ( '/ fire / order', this .baseURL);
14  
15          return fetch (url.toString (), {
 16,  
17             method: 'POST',
18 
19             headers: {'Content-Type': 'application/json'},
20 
21             body: JSON.stringify(entity)
22 
23         }).then(res => res.json());
24 
25     }
26 
27     public getOrder(id: number): Promise<Order> {
28 
29         const url = new URL('/api/order/' + id + '', this.baseURL);
30 
31         return fetch(url.toString(), {method: 'GET'}).then(res => res.json());
32 
33     }
34 
35 }
36 
37  

 

configuration

Due to greater flexibility, thus TypeScript Configuration through code generation. No configuration file. This can easily scale generator where it is needed. This is the simplest generator configurator:

 

 1    Rest2tsGenerator tsGenerator = new Rest2tsGenerator();
 2 
 3     // Java Classes filtering
 4 
 5     tsGenerator.setModelClassesCondition(new ExtendsJavaTypeFilter(BaseDTO.class));
 6 
 7     tsGenerator.setRestClassesCondition(new ExtendsJavaTypeFilter(BaseCtrl.class));
 8 
 9     // Java model classes converter setup
10 
11     JacksonObjectMapper jacksonObjectMapper = new JacksonObjectMapper();
12 
13     jacksonObjectMapper.setFieldsVisibility(JsonAutoDetect.Visibility.ANY);
14 
15     modelClassesConverter = new ModelClassesToTsInterfacesConverter(jacksonObjectMapper);
16 
17     modelClassesConverter.setClassNameMapper(new SubstringClassNameMapper("DTO", ""));
18 
19     tsGenerator.setModelClassesConverter(modelClassesConverter);
20 
21     // Spring REST controllers converter
22 
23     restClassesConverter = new SpringRestToTsConverter(new Angular4ImplementationGenerator());
24 
25     restClassesConverter.setClassNameMapper(new SubstringClassNameMapper("Ctrl", "Service"));
26 
27     tsGenerator.setRestClassesConverter(restClassesConverter);
28 
29     // set of java root packages for class scanning
30 
31     javaPackageSet = Collections.singleton("com.blueveery.springrest2ts.examples");
32 
33     tsGenerator.generate(javaPackageSet, Paths.get("../target/ts-code"));
34 
35  

Article wrote here, thank you for watching. If lack of support, please add a comment.

The thumbs welcome more friends attention, and I elaborate architecture to explore those things.

Guess you like

Origin www.cnblogs.com/youruike1/p/12058308.html