Gathering detailed insights and metrics for spring-data-rest-js
Gathering detailed insights and metrics for spring-data-rest-js
Gathering detailed insights and metrics for spring-data-rest-js
Gathering detailed insights and metrics for spring-data-rest-js
js lib for java spring data rest service,work for node.js and commonjs in browser,use fetch API
npm install spring-data-rest-js
Typescript
Module System
Node Version
NPM Version
TypeScript (87.83%)
JavaScript (8.85%)
HTML (2.75%)
Shell (0.56%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
32 Stars
164 Commits
7 Forks
6 Watchers
2 Branches
1 Contributors
Updated on Sep 08, 2023
Latest Version
0.2.21
Package Id
spring-data-rest-js@0.2.21
Size
12.30 kB
NPM Version
3.9.5
Node Version
6.2.2
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
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.
1# for npm 2npm install spring-data-rest-js --save 3# for bower 4bower install spring-data-rest-js
then use it in commonjs env
1let spring = require('spring-data-rest-js');
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:
1<!DOCTYPE html> 2<html> 3<body> 4<script src="./dist/spring.js"></script> 5<script> 6 window.spring.post('/'); 7</script> 8</body> 9</html>
#####add query param in url
1let param1 = {name: '中'}; 2let param2 = {age: 23, academy: 'physics'}; 3let request = spring.get(spring.requestConfig.baseURL).queryParam(param1); 4assert.equal(request.options.url, spring.requestConfig.baseURL + '?name=中'); 5request.queryParam(param2); 6assert.equal(request.options.url, spring.requestConfig.baseURL + '?age=23&academy=physics');
#####send request body as json
1let param = {name: '吴浩麟', age: 23}; 2let request = spring.post('/').jsonBody(param); 3assert.equal(request.options.body, JSON.stringify(param)); 4assert.equal(request.options.headers['Content-Type'], 'application/json');
#####send request body as form
1let param = {name: '中国', age: 123}; 2let request = spring.post('/postForm').formBody(param); 3assert.equal(request.options.headers['Content-Type'], 'application/x-www-form-urlencoded'); 4request.send().then(json=> { 5 assert.equal(json.name, '中国'); 6 assert.equal(json.age, 123); 7}).catch(err=> { 8 done(err); 9});
#####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
1spring.requestConfig.baseURL = 'http://localhost:8080/'; 2let req = spring.get('//hello/name//'); 3assert.equal(req.options.url, `http://localhost:8080/hello/name/`); 4let req2 = spring.get('https://google.com//hello/name'); 5assert.equal(req2.options.url, `https://google.com/hello/name`);
1spring.request.config = { 2 /** 3 * options used to every fetch request 4 */ 5 globalFetchOptions: { 6 headers: { 7 'Content-Type': 'application/json' 8 }, 9 credentials: 'same-origin' 10 }, 11 12 /** 13 * fetch request base url 14 * notice: must end with / 15 * @type {string} 16 */ 17 baseURL: '/', 18 /** 19 * call before send fetch request 20 * default do nothing 21 * @param {SpringRequest} request SpringRequest ref 22 */ 23 fetchStartHook: null, 24 /** 25 * call after fetch request end 26 * default do nothing 27 * @param {SpringRequest} request SpringRequest ref 28 */ 29 fetchEndHook: null 30};
fetch API request options see detail
1spring.requestConfig.globalFetchOptions = { 2 method: 'POST', 3 headers: { 4 'Accept': 'application/json', 5 'Content-Type': 'application/json' 6 }, 7 body: JSON.stringify({ 8 name: 'Hubot', 9 login: 'hubot', 10 }), 11 credentials: 'same-origin' 12}
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
1let classroom = new Classroom({name: 'D1143'}); 2let request; 3classroom.save().then(function () { 4 request = spring.get(`${Classroom.entityBaseURL()}/${classroom.id}`); 5 return request.send(); 6}).then(json=> { 7 assert.equal(json.constructor, Object); 8 assert.equal(json.name, 'D1143'); 9 assert.deepEqual(json, request.responseData); 10}).catch(err=> { 11 done(err); 12});
1let student = new Student({name: '吴浩麟', age: 23}); 2let academy = new Academy({name: '计算机学院'}); 3student.set('academy', academy); 4student.save().then(()=> { 5 return spring.get(`${Student.entityBaseURL()}/${student.id}`).follow(['self', 'academy', 'self', 'self']); 6}).then((json)=> { 7 assert.equal(json.name, '计算机学院'); 8}).catch(err=> { 9 done(err); 10});
before send fetch request
1let flag = 'old'; 2let request = spring.get(spring.requestConfig.baseURL); 3spring.requestConfig.fetchStartHook = function (req) { 4 assert.equal(req, request); 5 flag = 'new'; 6}; 7request.send().then(()=> { 8 assert.equal(flag, 'new'); 9}).catch(err=> { 10 done(err); 11});
fetch request is finished
1let flag = 'old'; 2let request = spring.get(spring.requestConfig.baseURL); 3spring.requestConfig.fetchEndHook = function (req) { 4 assert.equal(req, request); 5 flag = 'new'; 6}; 7request.send().then(()=> { 8 assert.equal(flag, 'new'); 9}).catch(err=> { 10 done(err); 11});
get a class by entity path name.
1//by extend function 2let Student = spring.extend('students'); 3let Academy = spring.extend('academies'); 4let Classroom = spring.extend('classrooms');
1//by typescript extend 2import * as spring from './index' 3import * as assert from 'assert'; 4class Student extends spring.Entity { 5 6 get name():string { 7 return this.get('name'); 8 } 9 10 set name(name:string) { 11 this.set('name', name); 12 } 13 14 hi():string { 15 return `${this.name}:${this.get('age')}`; 16 } 17} 18Student.entityName = 'students'; 19 20//use it 21let student = new Student({ 22 name: 'Hal', 23 age: 23 24}); 25assert.equal(student.name, 'Hal'); 26assert.equal(student.hi(), 'Hal:23');
1config = { 2 /** 3 * spring-data-rest-base-path config 4 * @type {string} 5 */ 6 restBaseURL: '' 7}; 8
class ref to spring data entity,use entity class to make a new entity instance and then create it on service.
1let student = new Student(); 2student.set('name', 'Tom'); 3student.save().then(()=> { 4 assert(student.id != null); 5 return spring.get(`${Student.entityBaseURL()}/${student.id}`).send(); 6}).then((json)=> { 7 assert.equal(json.name, 'Tom'); 8}).catch(err=> { 9 done(err); 10})
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 entity1let student = new Student(); 2student.id = 26;
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.
1let academy = new Academy({name: 'Math'}); 2academy.save().then(()=> { 3 academy.set('name', 'Physics'); 4 return academy.save(); 5}).then(()=> { 6 assert.deepEqual(academy.get('name'), 'Physics'); 7}).catch(err=> { 8 done(err); 9})
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()
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.
use entity's remove()
method to remove this entity in service.
1let student = new Student(); 2student.save().then(()=> { 3 return student.remove(); 4}).then(()=> { 5 return Student.findOne(student.id); 6}).catch(err=> { 7 assert.equal(err.response.status, 404); 8});
Entity Entity also has a static method to remove an entity by id
1Student.remove(42).then(()=>{},err=>{})
entity's data properties store in data
1let name = 'Ace'; 2let age = 20; 3let ace = new Student({name: name, age: age}); 4let student = new Student(); 5ace.save().then(()=> { 6 student.id = ace.id; 7 return student.fetch(); 8}).then(json=> { 9 assert.equal(json.name, name); 10 assert.equal(json.age, age); 11 assert.equal(student.get('name'), name); 12 assert.equal(student.get('age'), age); 13}).catch(err=> { 14 done(err); 15});
send request follow this entity's _links's href
1let student = new Student({name: '吴浩麟', age: 23}); 2let academy = new Academy({name: '计算机学院'}); 3student.set('academy', academy); 4student.save().then(()=> { 5 return student.follow(['academy']); 6}).then((json)=> { 7 assert.equal(json.name, '计算机学院'); 8}).catch(err=> { 9 done(err); 10});
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)
1let academy = new Academy({name: 'CS'}); 2let student = new Student({name: 'a', academy: academy}); 3student.save().then(()=> { 4 return Student.findOne(student.id); 5}).then(stu=> { 6 student = stu as Student; 7 return stu.fetchProperty('academy', Academy); 8}).then((academy)=> { 9 assert.equal(student.get('academy'), academy); 10 assert(academy instanceof Academy); 11 assert.equal(academy.get('name'), 'CS'); 12})
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)
1let classroom = new Classroom({name: 'java'}); 2let student = new Student({name: 'a', classrooms: [classroom]}); 3student.save().then(()=> { 4 return Student.findOne(student.id); 5}).then(stu=> { 6 student = stu as Student; 7 return stu.fetchArrayProperty('classrooms', Classroom); 8}).then(classrooms=> { 9 assert.deepEqual(student.get('classrooms'), classrooms); 10 assert.equal(classrooms.length, 1); 11 assert.equal(classrooms[0].get('name'), 'java'); 12})
get an entity instance by id
1let classRoom = new Classroom({name: '东16412'}); 2classRoom.save().then(()=> { 3 return Classroom.findOne(classRoom.id); 4}).then(entity=> { 5 assert.equal(entity.get('name'), '东16412'); 6}).catch(err=> { 7 done(err); 8});
get an not exist instance will reject 404 err
1Student.findOne('404404').then(()=> { 2 done('should be 404 error'); 3}).catch(req=> { 4 assert.equal(req.response.status, 404); 5})
support projection
1let student = new Student({name: 'HalWu', age: 23}); 2student.save().then(()=> { 3 return Student.findOne(student.id, {projection: 'NoAge'}); 4}).then(entity=> { 5 assert.equal(entity.get('name'), 'HalWu'); 6 assert.equal(entity.get('age'), null); 7}).catch(err=> { 8 done(err); 9})
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
1let size = 13; 2let pageIndex = 1; 3Student.findAll({page: pageIndex, size: size, sort: 'age,desc'}).then(function (jsonArr) { 4 assert(Array.isArray(jsonArr)); 5 assert.equal(jsonArr.length, size); 6 assert.equal(spring.extend.isEntity(jsonArr[0]), true); 7 assert.equal(jsonArr[0].constructor, Student); 8 assert.equal(arr['page'], {size: size, totalElements: 1, totalPages: 1, number: 0}); 9 for (let i = 1; i < size - 2; i++) { 10 assert.equal(jsonArr[i].get('age') > jsonArr[i + 1].get('age'), true); 11 assert.equal(jsonArr[i - 1].get('age') > jsonArr[i].get('age'), true); 12 } 13}).catch(req=> { 14 done(req); 15});
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
1Student.search('ageGreaterThan', {age: 1013, page: 1, size: 5, sort: 'age,desc'}).then(entityList=> { 2 assert.equal(entityList.length, 5); 3 for (var i = 0; i < entityList.length - 2; i++) { 4 assert(entityList[i].get('age') > entityList[i + 1].get('age')); 5 } 6}).catch(err=> { 7 done(err); 8});
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:
1let StudentX = spring.extend('students'); 2StudentX.exposeProperty('name'); 3StudentX.exposeProperty('age'); 4let student = new StudentX({ 5 name: 'hal' 6}); 7assert.equal(student['name'], 'hal'); 8student['age'] = 23; 9assert.equal(student.get('age'), 23);
implements source code:
1Object.defineProperty(this.prototype, propertyName, { 2 get: function () { 3 return this.get(propertyName); 4 }, 5 set: function (value) { 6 this.set(propertyName, value); 7 }, 8 enumerable: true 9})
all error will be reject by return promise,and the error object is instance of SpringRequest
will SpringRequest.error
properties store error reason
1Student.findOne(404).then(()=>{}).catch(req=>{ 2 console.error(req.error); 3 console.log(req.response.status); 4 console.log(req.response.statusText); 5})
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.
this lib write with typescript, run typings install
to install require typescript d.ts file, edit *.ts file then test it,
test with mocha
,run npm run test
to test it
after test success,run sh ./release.sh
to commit it to github and npm.
Copyright (c) 2016 HalWu
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
license file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2025-07-14
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More