当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

angular-spring-data-rest

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 柳杰
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

angular-spring-data-rest

An AngularJS module with an additional interceptor which eases the work with a Spring Data REST backend.

See how it works

If you want to see the module in action, then check out the sample application which runs with Spring Boot and is super easy to setup: angular-spring-data-rest-sample

Table of contents

Quick start

To use the SpringDataRestAdapter Angular module with bower execute the following command to install the package:

bower install angular-spring-data-rest

or with npm:

npm install angular-spring-data-rest

Overview

Spring Data REST integrates Spring HATEOAS by default. This simplifies the creation of REST presentations which are generated with the HATEOAS principle.

Therefore the Spring Data REST responses have resources and embedded resources like in the following JSON response example:

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/categories{?page,size,sort}",
            "templated": true
        }
    },
    "_embedded": {
        "categories": [
            {
                "name": "Test category 1",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/categories/1"
                    },
                    "parentCategory": {
                        "href": "http://localhost:8080/categories/1/parentCategory"
                    }
                }
            },
            {
                "name": "Test category 2",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/categories/2"
                    },
                    "parentCategory": {
                        "href": "http://localhost:8080/categories/2/parentCategory"
                    }
                }
            }
        ]
    },
    "page": {
        "size": 20,
        "totalElements": 2,
        "totalPages": 1,
        "number": 0
    }
}

The above response is the result of calling the endpoint to get all categories(http://localhost:8080/categories). It contains the _links property which holds an object with several named resources(e.g. self). These resources are used to navigate to a related entity(e.g. parentCategory) or to a specific endpoint defined by the backend.

The _embedded property holds an array of the requested items, and each of the items has again a _links property which defines the resources for the specific item. You can find more about how the responses of Spring Data REST look like here.

This Angular module provides two ways of processing a response from the Spring Data REST backend and ease the usage with the resources and embedded items:

  1. Using an instance of the SpringDataRestAdapter.
  2. Add the SpringDataRestInterceptor to the Angular $httpProvider.interceptors such that all responses are processed.

The SpringDataRestAdapter

The spring-data-rest Angular module provides a provider for the SpringDataRestAdapter object. This object is the core of the module and it processes a given response and adds the following additional properties/methods to it:

  1. _resources: this method wraps the Angular $resource function by default (this is exchangeable) and adds an easy way to retrieve the resources defined in the _links property. It is also used to retrieve all available resources of the given object. Read more about this method here.
  2. _embeddedItems: this property replaces the _embedded property and sets the named array (categories in the upper example response) with the embedded items as its value. Read more about this property here.

Spring Data REST also generates an index response when you make a GET response to the configured base url of the dispatcher servlet. This response looks like the following example:

{
  "_links" : {
    "users" : {
      "href" : "http://localhost:8080/users{?page,size,sort}",
      "templated" : true
    },
    "categories" : {
      "href" : "http://localhost:8080/categories{?page,size,sort}",
      "templated" : true
    },
    "accounts" : {
      "href" : "http://localhost:8080/accounts{?page,size,sort}",
      "templated" : true
    },
    ...
  }
}

This response shows all configured Spring Data REST repositories and the links to these resources. The SpringDataRestAdapter is also able to handle this response and to provide an easy method to retrieve all the available resources with the _resources method. Please read more about this here.

Another feature is that the SpringDataRestAdapter is able to automatically fetch the links of a resource and adds the response of the link as a property to the main response. Please read more about this here.

Usage of SpringDataRestAdapter

To use the SpringDataRestAdapter object you need to include the angular-spring-data-rest.js file (or the minified version) and add the spring-data-rest module as a dependency in your module declaration:

var myApp = angular.module("myApplication", ["ngResource", "spring-data-rest"]);

Now you are able use the SpringDataRestAdapter object and process a given response and you will get a promise back which resolves with the processes response:

SpringDataRestAdapter.process(response).then(function(processedResponse) {
  ...
});

The response can be a String or a promise from an $http.get() call (or any other promise which resolves the response) like in the following example:

var httpPromise = $http.get('/rest/categories');

SpringDataRestAdapter.process(httpPromise).then(function (processedResponse) {
    $scope.categories = processedResponse._embeddedItems;
});

For simplicity the rest of the examples assume that you already have the response present. Please read on on how to use the _resources method and the _embeddedItems property to ease the handling of resources and embedded items.

Usage of _resources method

The _resources property is added on the same level of the JSON response object where a _links property exists. When for example the following JSON response object is given:

var response = {
    "_links": {
        "self": {
            "href": "http://localhost:8080/categories{?page,size,sort}",
            "templated": true
        }
    },
    "_embedded": {
        ...
    }
    ...
}

Then the SpringDataRestAdapter will add the _resources method to the same level such that you can call it the following way (inside the then function of the promise):

SpringDataRestAdapter.process(response).then(function(processedResponse) {
  processedResponse._resources(linkName, paramDefaults, actions, options);
});

This _resources method is added recursively to all the properties of the JSON response object where a _links property exists.

The _resources method parameters and return type

The _resources method takes the following four parameters:

  • linkName: the name of the link's href you want to call with the underlying Angular $resource function. You can also pass in a resource object with parameters in the following way:
SpringDataRestAdapter.process(response).then(function(processedResponse) {
  var resourceObject = {
    "name": "self",
    "parameters": {
        "size": 20,
        "sort": "asc"
    }
  }
  processedResponse._resources(resourceObject, paramDefaults, actions, options);
});

This will call Angular $resource method by default (this is exchangeable) with the href of the self resource and will add the parameters size and sort as query string to the URL. If the resource object parameters and the paramDefaults parameters are set, then these two objects are merged such that the resource object parameters appear first in the new object and the paramDefaults parameters last.

  • paramDefaults: the default values for url parameters. Read more here.
  • actions: custom action that should extend the default set of the $resource actions. Read more here.
  • options: custom settings that should extend the default $resourceProvider behavior Read more here.

You are also able to add URL templates to the passed in linkName parameter. (This just works if you pass a string and not a resource object) The following example explains the usage:

SpringDataRestAdapter.process(response).then(function(processedResponse) {
  var resources = processedResponse._resources("self/:id", {id: "@id"});
  var item = resources.get({id: 1}).then(function(data) {
    item = data;
  };
});

The _resources method returns the Angular resource "class" object with methods for the default set of resource actions. Read more here.

If no parameter is given the _resources method will return all available resources objects of the given object. When for example the following JSON response object is given:

var response = {
    "_links": {
        "self": {
            "href": "http://localhost:8080/categories{?page,size,sort}",
            "templated": true
        },
        "parentCategory": {
            "href": "http://localhost:8080/categories/1/parentCategory"
        }
    },
    "_embedded": {
        ...
    }
    ...
}

Then the following call to the _resources method without any parameter will return an array of all available resource objects.

SpringDataRestAdapter.process(response).then(function(processedResponse) {
  var availableResources = processedResponse._resources();
});

The above call will result in the following return value:

[
    {
        "name":"self",
        "parameters": {
            "page": "",
            "size": "",
            "sort": ""
        }
    },
    {
        "name":"parentCategory"
    }
]

This functionality is useful if you want to first check all available resources before using the _resources method to retrieve the specific resource.

_resources usage example

This example refers to the JSON response in the Overview. If you want to get the parent category of a category you would call the _resources method the following way:

SpringDataRestAdapter.process(response).then(function(processedResponse) {
  var parentCategoryResource = processedResponse._embeddedItems[0]._resources("parentCategory");

  // create a GET request, with the help of the Angular resource class, to the parent category
  // url and log the response to the console
  var parentCategory = parentCategoryResource.get(function() {
    console.log("Parent category name: " + parentCategory.name);
  });
});

Exchange the underlying Angular $resource function

If you want to exchange the underlying call to the Angular $resource method then you are able to do this within the configuration of the SpringDataRestAdapter. By default it will use the Angular $resource function.

The following example shows how to set a custom function:

myApp.config(function (SpringDataRestAdapterProvider) {

    // set the new resource function
    SpringDataRestAdapterProvider.config({
        'resourcesFunction': function (url, paramDefaults, actions, options) {
            // do the call to the backend and return your desired object
        }
    });
});

The description of the parameters you will find here. You can also read more about the configuration of the SpringDataRestAdapter here (and how to use the $http service in the configuration phase)

Usage of _embeddedItems property

The _embeddedItems property is just a convention property created by the SpringDataRestAdapter to easily iterate over the _emebedded items in the response. Like with the _resources method, the SpringDataRestAdapter will recursively create an _embeddedItems property on the same level as a _embedded property exists for all the JSON response properties.

_embeddedItems usage example

This example refers to the JSON response in the Overview. If you want to iterate over all categories in the response you would do it in the following way:

SpringDataRestAdapter.process(response).then(function(processedResponse) {

  // log the name of all categories contained in the response to the console
  angular.forEach(processedResponse._embeddedItems, function (category, key) {
    console.log("Category name: " + category.name);
  });
});

Be aware that the original _embedded property gets deleted after the SpringDataRestAdapter processed the response.

How to automatically fetch links

The SpringDataRestAdapter is able to fetch specified links automatically. This means that if you have the following response:

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/categories{?page,size,sort}",
            "templated": true
        },
        "anotherLink": {
            "href": "http://localhost:8080/anotherLink"
        }
    },
    ...
}

and you want to fetch the data from the anotherLink link then you just need to pass the link name to the SpringDataRestAdapter process function:

SpringDataRestAdapter.process(response, 'anotherLink').then(function(processedResponse) {
  var fetchedObject = processedResponse.anotherLink;
});

Now you are able to get the data from the processed resource by just accessing the property named anotherLink.

The SpringDataRestAdapter by default adds the response of the link to a property in the original response with the same name as the link.

If you want to process the returned response again with the SpringDataRestAdapter then you are able to set the recursive flag when creating it:

SpringDataRestAdapter.process(response, 'anotherLink', true).then(function(processedResponse) {
  ...
});

Now the response of the anotherLink will be processed the same way as the main response was processed. But be aware when setting the recursive flag to true, because when your responses of the links contain the same link name again, then it will end up in a infinite loop.

It will not fetch the self link as this would make no sense because the data is already in the response. The self key is also configurable. Read more here.

As a last configuration option you are able to set the fourth parameter called fetchMultiple of the process method which is used to define if a link is fetched multiple times if the same link is contained in multiple links and you want to resolve each one of them. The drawbackis that it won't cache the responses in any way. So if you enable this then multiple network calls will be made. Here an example:

SpringDataRestAdapter.process(response, 'anotherLink', true, true).then(function(processedResponse) {
  ...
});

⚠️ If you set the fetchMultiple to true you could end up in an infinite loop if you have circular dependencies in your _links.

Fetch multiple or all links

If you want to fetch multiple links then you are able to add an array of strings with the given link names:

SpringDataRestAdapter.process(response, ['anotherLink', 'testLink']).then(function(processedResponse) {
  ...
});

and if you want to fetch all links, then you can use the predefined and also configurable fetchAllLinkNamesKey:

SpringDataRestAdapter.process(response, '_allLinks').then(function(processedResponse) {
  ...
});

Please read more here on how to configure the fetchAllLinkNamesKey.

Exchange the underlying fetch function

If you want to exchange the underlying function to fetch the links then you are able to do this within the configuration of the SpringDataRestAdapter. By default it will use the Angular $http function.

The following example shows how to set a custom function:

myApp.config(function (SpringDataRestAdapterProvider) {

    // set the new resource function
    SpringDataRestAdapterProvider.config({
        'fetchFunction': function (url, key, data, fetchLinkNames, recursive) {
            // fetch the url and add the key to the data object
        }
    });
});

The description of the parameters you will find here. You can also read more about the configuration of the SpringDataRestAdapter here (and how to use the $http service in the configuration phase)

The fetch method parameters

The parameters for the fetch method are the following:

  • url: The url of the link from which to fetch the data.
  • key: The name of the link which is used to name the property in the data object.
  • data: The data object in which the new property is created with the response of the called url.
  • fetchLinkNames: The fetch link names to allow to process the fetched response recursiveley
  • recursive: True if the fetched response should be processed recursively, false otherwise.

How to use SpringDataRestAdapter with promises

The SpringDataRestAdapter is also able to process promises instead of data objects. The data object which is passed to the specified promise when it is resolved needs to be in the following formats:

{
    data: {
        "_links": {
            "self": {
                "href": "http://localhost:8080/categories{?page,size,sort}",
                "templated": true
            },
            "anotherLink": {
                "href": "http://localhost:8080/anotherLink"
            }
        },
        // the rest of the JSON response
        ...
    }
}

or

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/categories{?page,size,sort}",
            "templated": true
        },
        "anotherLink": {
            "href": "http://localhost:8080/anotherLink"
        }
    },
    // the rest of the JSON response
    ...
}

The data property of the second format of the promise object is the JSON response of the back end. To process such a promise you need to call the SpringDataRestAdapter like in the following example:

SpringDataRestAdapter.process(promise).then(function(processedResponse) {
    // you can now use the processedResponse as any other processed response from the SpringDataRestAdapter
};

You can also right away use the promise support with the Angular $http.get() method like in the following example:

SpringDataRestAdapter.process($http.get('categories')).then(function(processedResponse) {
    $scope.categories = processedResponse._embeddedItems;
};

Configuration of the SpringDataRestAdapter

The SpringDataRestAdapter is designed to be configurable and you are able to configure the following properties:

  • linksKey (default: _links): the property name where the resources are stored.
  • linksHrefKey (default: href): the property name where the URL is stored in a link object.
  • linksSelfLinkName (default: self): the name of the self link in the links object.
  • embeddedKey (default: _embedded): the property name where the embedded items are stored.
  • embeddedNewKey (default: _embeddedItems): the property name where the array of embedded items are stored.
  • embeddedNamedResources (default: false): true if the embedded resources names (can be more than one) should beleft as is, false if they should be removed and be replaced by the value of the first embedded resource
    • Example if set to true:
    {
        ...
        "_embeddedItems": {
            "categories": [...]
        }
        ...
    }
    • Example if set to false:
    {
        ...
        "_embeddedItems": [...]
        ...
    }
  • hrefKey (default: href): the property name where the url is stored under each specific link.
  • resourcesKey (default: _resources): the property name where the resource method is stored.
  • resourcesFunction (default: undefined): the function to use to call the backend. Read more how to do this here
  • fetchFunction (default: undefined): the function to use to fetch data from the backend. Read more how to do this here
  • fetchAllKey (default: _allLinks): the key to pass to the SpringDataRestAdapter to fetch all available links

You are able to configure the SpringDataRestAdapter provider in a Angular configuration block in the following way:

myApp.config(function (SpringDataRestAdapterProvider) {

    // set the links key to _myLinks
    SpringDataRestAdapterProvider.config({
        'linksKey': '_myLinks'
    });
});

The config method of the SpringDataRestAdapterProvider takes a configuration object and you are able to override each value or completely replace the whole configuration object. The default configuration object looks like this:

{
    "linksKey": "_links",
    "linksHrefKey": "href",
    "linksSelfLinkName": "self",
    "embeddedKey": "_embedded",
    "embeddedNewKey": "_embeddedItems",
    "embeddedNamedResources": false,
    "resourcesKey": "_resources",
    "resourcesFunction": undefined,
    "fetchFunction": undefined,
    "fetchAllKey": "_allLinks"
}

If you want to use the $http service inside the fetch function in the configuration phase then you need to use the Angular injector to get the $http service:

myApp.config(function (SpringDataRestAdapterProvider) {

    // set the new fetch function
    SpringDataRestAdapterProvider.config({
        fetchFunction: function (url, key, data, fetchLinkNames, recursive) {
            var $http = angular.injector(['ng']).get('$http');

            $http.get('/rest/endpoint').then(function (responseData) {
                console.log(responseData);
            })
        }
    });
});

The SpringDataRestInterceptor

If you want to use the SpringDataRestAdapter for all responses of the Angular $http service then you can add the SpringDataRestInterceptor to the $httpProvider.interceptors in an Angular configuration block:

myApp.config(function (SpringDataRestInterceptorProvider) {
    SpringDataRestInterceptorProvider.apply();
});

The apply method will automatically add the SpringDataRestInterceptor to the $httpProvider.interceptors.

Dependencies

The spring-data-rest Angular module requires the ngResource Angular module.

Release notes

Check them here: Release notes

Acknowledgements

When I first searched for an Angular module for Spring Data REST I just found the marvelous project of Jeremy which is useful if you just use Spring HATEOAS. So please have a look at his angular-hateoas project because he gave me the full permissions to use his code base and project structure for this project here. At this point I want to thank him for his nice work.

License

This Angular module is available under the MIT license.

(c) All rights reserved Guy Brand

  • REST(表征性状态传输,Representational State Transfer)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。RESTful风格的设计不仅具有更好的可读性(Human Readable),而且易于做缓存以及服务器扩展(scalability)。REST风格体现在URL设计上: 每个URL对应一个资源 对资源的不同操作对应于HTTP的不同

  • 案例概述 在本系列的第一篇文章中,我们将探索一种用于REST API的简单查询语言。我们将充分利用Spring作为REST API,并将JPA 2标准用于持久性方面。 **为什么使用查询语言?**因为 - 对于任何复杂的API - 通过非常简单的字段搜索/过滤资源是不够的。查询语言更灵活,允许您精确过滤所需的资源。 User Entity 首先 - 让我们提出我们将用于过滤器/搜索API的简单实体

  • jsp技术已经不再推荐,现在更加流行前后端分离,即静态html+ rest接口(json格式),具体原因本篇不讨论,本博客只讲html+rest模式。 老版本rest 用spring mvc可以很容易的实现json格式的rest接口,以下是spring老版本的用法,在spring boot中已经自动配置了jackson //注册一个spring控制层bean @Controller publi

  • $http是AngularJS提供的一个核心Service,通过浏览器的XMLHttpRequest或JSONP与服务器进行交互。 这是一个非常常用的Service,类似于jQuery提供的AJAX。与jQuery类似,$http也采用了deferred/promise模式,不同的是Angular的deferred/promise模式是由Angular的$qService来提供的。 在Angula

  • 文章参考 www.itying.com 在 app.module.ts 中引入 HttpClientModule 并注入 import {HttpClientModule} from '@angular/common/http'; imports: [ BrowserModule, HttpClientModule ] Angular get 请求数据 在用到的地方引入 HttpClie

  • 1.1. 前述: ng中的$http用于请求后台数据,类似于js用的ajax和jq中的$.ajax 在ng的$http中的方法有 0、$http 1、$http.get 2、$http.head 3、$http.post 4、$http.put 5、$ht

 相关资料
  • angular-data 是 AngularJS 的一个扩展,实现了数据存储和缓存的功能。 示例代码: var app = angular.module('myApp', ['angular-data.DS']);app.factory('User', function (DS) {  // Simplest resource definition  return DS.defineResourc

  • Angular ngrx-data This repository is now merged with @ngrx into @ngrx/data. You can find the ngrx/data docs here and the github repository with ngrx/data in it here Please read the note above Zero Ngr

  • 我看了一下下面的问题 与SpringDataJPA相比,使用SpringDataREST有哪些优势? 它不太符合我的需要。我的数据库在MYSQL上,我选择了Spring-Data-JPA实现。REST能给我带来哪些我在简单的Spring-Data-JPA中找不到的额外优势?例如,如果明天,我决定实现缓存b/w我的业务和数据库模块,在这种情况下,我将不得不写较小的代码?哪个容易配置?哪一个更灵活,如

  • Spring Data REST 的目标是提供坚实的基础,从而使用 HTTP REST 语义来开放 CRUD 操作到你的 JPA 库管理的实体。 这个端口的首次实现使用 Spring MVC 以及标准的 Servlet 架构,从而简单的包括你的域类和他们的对应库定义,轻松将一个 WAR 文集那部署成一个全面的 CRUD 应用程序。以后的实现将允许你通过使用高通量非阻塞的IO,在 non-Servl

  • Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问计数,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。 Spring Data 包含多个子项目: Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化 Hadoop - 基于 Spring 的 Hadoop 作业配置和一个 POJO 编程模

  • 问题内容: 在哪些典型的现实生活场景中,人们会选择Spring Data JDBC / Spring Data JPA与Hibernate?我想了解最适合这两种实现方式的场景。 问题答案: 正如@Naros所说,标题中当前存在的问题实际上并没有解决。似乎我们应该真正看一下4个选项,并且主要列出每种方法的优点,缺点是没有其他方法的优点: 没有Spring数据的JDBC 您可以对所发生的事情进行100