Spring Data Rest JavaScript Library
Spring Data Rest is makes it easy to build hypermedia-driven REST web services. This lib provider useful util to play with the service in js. It's a easy to use and lightweight (2kb after min and gzip) javascript lib can run in both node.js and browser,can be work with lib like AngularJS React Vue. support Typescript.
Installation
# for npm npm install spring-data-rest-js --save# for bower bower install spring-data-rest-js
then use it in commonjs env
let spring = ;
for browser,you can use tools like Webpack or Browserify to bundle up your module for browser. you also can include lib file in html file and then use it:
SpringRequest
Build SpringRequest
add query param in url
let param1 = name: '中';let param2 = age: 23 academy: 'physics';let request = spring;assert;request;assert;
send request body as json
let param = name: '吴浩麟' age: 23;let request = spring;assert;assert;
send request body as form
let param = name: '中国' age: 123;let request = spring;assert;request;
auto revise url
if path param is a complete url then fetch ues path as url, else path is not a complete url string but just a path then fetch url=config.baseURL+path url string will been auto revised, etc: http://localhost/api//user///id/ will convert to http://localhost/api/user/id
springrequestConfigbaseURL = 'http://localhost:8080/';let req = spring;assert;let req2 = spring;assert;
Config SpringRequest
springrequestconfig = /** * options used to every fetch request */ globalFetchOptions: headers: 'Content-Type': 'application/json' credentials: 'same-origin' /** * fetch request base url * notice: must end with / * @type */ baseURL: '/' /** * call before send fetch request * default do nothing * @param */ fetchStartHook: null /** * call after fetch request end * default do nothing * @param */ fetchEndHook: null;
Fetch API Global Option
fetch API request options see detail
springrequestConfigglobalFetchOptions = method: 'POST' headers: 'Accept': 'application/json' 'Content-Type': 'application/json' body: JSON credentials: 'same-origin'
Get Response
request return response in Promise
,if request success Promise
will resolve json data,if will reject a SpringRequest
object will SpringRequest.error
store error reason
send request and get response data
let classroom = name: 'D1143';let request;classroom;
follow links
let student = name: '吴浩麟' age: 23;let academy = name: '计算机学院';student;student;
fetch global hook
before send fetch request
let flag = 'old';let request = spring;springrequestConfig { assert; flag = 'new';};request;
fetch request is finished
let flag = 'old';let request = spring;springrequestConfig { assert; flag = 'new';};request;
Entity
extend
get a class by entity path name.
//by extend functionlet Student = spring;let Academy = spring;let Classroom = spring;
//by typescript extend;Student.entityName = 'students'; //use it;assert.equalstudent.name, 'Hal';assert.equalstudent.hi, 'Hal:23';
config entity
config = /** * spring-data-rest-base-path config * @type */ restBaseURL: '';
create entity
class ref to spring data entity,use entity class to make a new entity instance and then create it on service.
let student = ;student;student
id
the entity instance's id. for a existed entity set instance's id then you can use instance
fetch
method to fetch entity's datasave
method to update entity's updated propertiesremove
method to delete this entity
let student = ;studentid = 26;
update entity
if a entity instance has id attr,and use entity's set(key,value)
method update attr,then can call entity's save()
method to patch update change to service.
let academy = name: 'Math';academy
save or update
create or update entity if id properties is set,then will send HTTP PATCH request to update an entity(will watch change in data properties to track change fields) if id is null,then will send HTTP POST request to create an entity. if entity.properties is an instance of Entity or Entity[],then entity.properties.save() will also call,which mean entity's all Entity attr will auto save()
track modify fields
every Entity instance has attr modifyFields
fields name array,which store field has been changed.
when update modify to service, modifyFields
is used to optimize a mini PATCH
request but send whole attr.
when call Entity's set
method,will compare olaValue and newValue,if value is equal then not append filed name to modifyFields.
remove entity
use entity's remove()
method to remove this entity in service.
let student = ;student;
Entity Entity also has a static method to remove an entity by id
Student
fetch data
entity's data properties store in data
let name = 'Ace';let age = 20;let ace = name: name age: age;let student = ;ace;
follow
send request follow this entity's _links's href
let student = name: '吴浩麟' age: 23;let academy = name: '计算机学院';student;student;
fetch relation property
fetch relation property and store response value in entity's data attr,relation property is an instance of Entity.
after fetch you can get relation property by entity.get(propertyName)
let academy = name: 'CS';let student = name: 'a' academy: academy;student
fetch array type relation property
fetch relation property and store response value in entity's data attr,relation property is an Entity array
after fetch you can get relation property by entity.get(propertyName)
let classroom = name: 'java';let student = name: 'a' classrooms: classroom;student
Entity static methods
findOne
get an entity instance by id
let classRoom = name: '东16412';classRoom;
get an not exist instance will reject 404 err
Student
support projection
let student = name: 'HalWu' age: 23;student
findAll
collection resource with page and sort.
Returns all entities the repository servers through its findAll(…) method. If the repository is a paging repository we include the pagination links if necessary and additional page metadata.*
return entity array has page
attr patch form response json data's page info
- @param {number} opts.page the page number to access (0 indexed, defaults to 0).
- @param {number} opts.size the page size requested (defaults to 20).
- @param {string} opts.sort a collection of sort directives in the format ($propertyName,)+[asc|desc]?
let size = 13;let pageIndex = 1;Student;
search
search resource if the backing repository exposes query methods.
call query methods exposed by a repository. The path and name of the query method resources can be modified using @RestResource on the method declaration.
return entity array has page
attr patch form response json data's page info
- @param {string} searchPath spring data rest searchMethod path string
- @param {Object} opts search params, If the query method has pagination capabilities (indicated in the URI template pointing to the resource) the resource takes the following parameters:
- @param {number} opts.page the page number to access (0 indexed, defaults to 0).
- @param {number} opts.size the page size requested (defaults to 20).
- @param {string} opts.sort a collection of sort directives in the format ($propertyName,)+[asc|desc]?
Student;
exposeProperty
expose entity instance properties in _data to entity itself use Object.defineProperty getter and setter after expose,you can access property in entity by entity.property rather than access by entity.data().property. example:
let StudentX = spring;StudentX;StudentX;let student = name: 'hal';assert;student'age' = 23;assert;
implements source code:
Object
Error Handle
all error will be reject by return promise,and the error object is instance of SpringRequest
will SpringRequest.error
properties store error reason
Student
Example Code
- unit test source code javascript,typescript java
- real app typescript java
API Doc
Browser Support
this lib use es6 some feature:
for browser use, be sure browser must support this,in old browser you should include polyfill.
require es6 Object.assign
and Promise
,this lib build on the top of es6 fetch API.
In Node.js env,will use node-fetch as fetch polyfill.
Contributing
dev
this lib write with typescript, run typings install
to install require typescript d.ts file, edit *.ts file then test it,
test
test with mocha
,run npm run test
to test it
commit and release
after test success,run sh ./release.sh
to commit it to github and npm.
require
- spring java backend service java code for test use
- tsc to compile typescript file
- webpack for pack commonjs to browser
- mocha for test
- typings for install require typescript d.ts file
- typedoc for build API doc
License
Copyright (c) 2016 HalWu