This template provides simple way to wrap RESTful service as JavaScript API.
Keywords:
- rest
- template-rest
After cloning this template, you can test first.
- Modify endpoint in
test/FetchTemplateWebService-testx.js
.
var endpoint = "http://address:port/yourapp/api/subjectName"; // modify here
var serv = new rest.FetchTemplateWebService(endpoint);
serv.queryAll(result => console.log(result));
-
Make sure that endpoint is a
GET
API without any parameters. -
Test.
npm run testfetch
- Build.
npm run build
template-rest.js and template-rest.min.js are outputed to dist folder.
All implement simple GET/POST/PUT/DELETE methods.
- Use Fetch to send the request.
- Use Promise to handle the response.
- Use XMLHttpRequest to send the request.
- Use callback function to handle the response.
All templates provide default implementation of
- insert
- update
- delete
- queryAll
- queryOne
- Extend from FetchWebService.
- Extend from XHRWebService.
export default {
output: {
name: "rest" // define namespace
}
};
{
"name": "template-rest" // define output file name
}
Suppose there is a web service about user
information:
- COPY, PASTE one template and RENAME to UserWebService.
- Modify this.url in the file to actual endpoint.
- Add new methods based on your API.
- Test.
var apiURL = "http://localhost:8080/some-app/api/v1";
var xhr = new XMLHttpRequest();
xhr.open("GET", apiURL + "/users"); // nightmare if 'users' changed
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function() {
var result = JSON.parse(xhr.responseText);
// do something
}
xhr.send();
var apiURL = "http://localhost:8080/some-app/api/v1";
// 'users' appended in UserWebService
new UserWebService(apiURL).queryAll(
(result) => {
// do something
});
var apiURL = "http://localhost:8080/some-app/api/v1";
// 'users' appended in UserWebService
new UserWebService(apiURL).queryAll()
.then(result = > {
// do something
})
.catch();
- require("xmlhttprequest").XMLHttpRequest can not be used in the browser.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.