npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

spring-data-rest.js

v0.0.1

Published

js lib for java spring data rest service,work for node.js and commonjs in browser,use fetch API

Downloads

3

Readme

Spring Data Rest JavaScript Library

Build Status

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.

Installation

$ npm install springRest-data-rest.js --save

then use it in commonjs env

let springRest = require('spring-data-rest.js');

Request

Build Request

add query param in url

let request = springRest.request.get(springRest.request.config.restBasePath).query({page: 0, size: 2});
assert.equal(request.options.url, springRest.request.config.restBasePath + '?page=0&size=2');

send json as request body

let param = {name: '吴浩麟', age: 23};
let request = springRest.request.post('/').body(param);
assert.deepEqual(request.options.body, JSON.stringify(param));
assert.equal(request.options.headers['Content-Type'], 'application/json');

Config Request

springRest.request.config = {
    /**
     * options used to every fetch request
     */
    globalOptions: {},
    /**
     * API base url
     */
    basePath: 'http://api.hostname',
    /**
     * springRestRest data rest base url
     * @type {string}
     */
    restBasePath: 'http://api.hostname/rest'
};

Fetch API Global Option

fetch API request options see detail

springRest.request.config.globalOptions = {
   method: 'POST',
   headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
   },
   body: JSON.stringify({
        name: 'Hubot',
        login: 'hubot',
   }),
   credentials: 'same-origin'
}

Get Response

request return response in Promise,if request success Promise will resolve json data,if will reject a Request object will Request.error store error reason

get response data

let classroom = new Classroom({name: 'D1143'});
    classroom.save().then(function () {
    return springRest.request.get(`${Classroom.entityBaseURL}/${classroom.id}`).data();
}).then(function (data) {
    assert.equal(data.name, 'D1143');
    done();
}).catch(function (err) {
    done(err);
});

follow links

let student = new Student({name: '吴浩麟', age: 23});
    let academy = new Academy({name: '计算机学院'});
    student.set('academy', academy);
    student.save().then(()=> {
    return springRest.request.get(`${Student.entityBaseURL}/${student.id}`).follow(['self', 'academy', 'self', 'self']);
}).then((data)=> {
    assert.equal(data.name, '计算机学院');
    done();
}).catch(err=> {
    done(err);
});

Entity

extend get a class by entity path name

let Student = springRest.extend('students');
let Academy = springRest.extend('academies');
let Classroom = springRest.extend('classrooms');

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 = new Student();
   student.set('name', 'Tom');
   student.save().then(()=> {
   assert(student.id != null);
   return springRest.request.get(`${Student.entityBaseURL}/${student.id}`).data();
}).then((data)=> {
   assert.equal(data.name, 'Tom');
   done();
}).catch(err=> {
   done(err);
})

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 data
  • save method to update entity's updated properties
  • delete method to delete this entity
let student = new Student();
student.id = 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 = new Academy({name: 'Math'});
   academy.save().then(()=> {
   academy.set('name', 'Physics');
   return academy.save();
}).then(()=> {
   assert.deepEqual(academy.get('name'), 'Physics');
   done();
}).catch(err=> {
   done(err);
})

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

delete entity use entity's delete() method to remove this entity in service.

let student = new Student();
   student.save().then(()=> {
   return student.delete();
}).then(()=> {
   return Student.findOne(student.id);
}).catch(err=> {
   assert.equal(err.response.status, 404);
   done();
});

Entity Class also has a static method to delete an entity by id

Student.delete(42).then(()=>{},err=>{})

fetch data entity's data properties store in data

let name = 'Ace';
   let age = 20;
   let ace = new Student({name: name, age: age});
   let student = new Student();
   ace.save().then(()=> {
   student.id = ace.id;
   return student.fetch();
}).then(data=> {
   assert.equal(data.name, name);
   assert.equal(data.age, age);
   assert.equal(student.get('name'), name);
   assert.equal(student.get('age'), age);
   done();
}).catch(err=> {
   done(err);
});

Entity static methods

findOne get an entity instance by id

let classRoom = new Classroom({name: '东16412'});
classRoom.save().then(()=> {
    return Classroom.findOne(classRoom.id);
}).then(entity=> {
    assert.equal(entity.get('name'), '东16412');
    done();
}).catch(err=> {
    done(err);
});

get an not exist instance will reject 404 err

Student.findOne('404404').then(()=> {
    done('should be 404 error');
}).catch(req=> {
    assert.equal(req.response.status, 404);
    done();
})

findAll find entity list with page and sort method param opts = { page:'the page number to access (0 indexed, defaults to 0)', size:'the page size requested (defaults to 20)', sort:'a collection of sort directives in the format ($propertyName,)+[asc|desc]? etc:name,age,desc' }

let size = 13;
let pageIndex = 1;
Student.findAll({page: pageIndex, size: size, sort: 'age,desc'}).then(function (arr) {
    assert(Array.isArray(arr));
    assert.equal(arr.length, size);
    assert.equal(arr.page.number, pageIndex);
    assert.equal(arr.page.size, size);
    assert.equal(springRest.extend.isEntity(arr[0]), true);
    assert.equal(arr[0].constructor, Student);
    for (let i = 1; i < size - 2; i++) {
        assert.equal(arr[i].get('age') > arr[i + 1].get('age'), true);
        assert.equal(arr[i - 1].get('age') > arr[i].get('age'), true);
    }
    done();
}).catch(req=> {
    done(req);
});

Error Handle

all error will be reject by return promise,and the error object is instance of Request will Request.error properties store error reason

Student.findOne(42).then(()=>{}).catch(req=>{
    console.error(req.error);
    console.log(req.response.status);
    console.log(req.response.statusText);
})

Example

Browser Support

require es6 Object.assign and Promise,this lib build on the top of es6 fetch API,use isomorphic-fetch as polyfill. Browser Support

License

MIT

Copyright (c) 2016 HalWu