2
0
mirror of https://github.com/frappe/books.git synced 2024-12-23 03:19:01 +00:00

frappe.call

This commit is contained in:
Rushabh Mehta 2018-03-26 18:26:21 +05:30
parent a91489cfbc
commit fa049a37a1
4 changed files with 60 additions and 11 deletions

View File

@ -66,13 +66,7 @@ module.exports = class ReportPage extends Page {
const filterValues = this.getFilterValues();
if (filterValues === false) return;
let response = await fetch(this.url + '?' + frappe.getQueryString(filterValues), {
method: 'GET',
headers: {
Accept: 'application/json'
}
})
const data = await response.json();
let data = await frappe.call({method: this.method, args: filterValues});
this.datatable.refresh(data);
}

View File

@ -14,6 +14,8 @@ module.exports = {
frappe.registerModels(require('../models'), 'client');
frappe.fetch = window.fetch.bind();
this.setCall();
frappe.db = await new HTTPClient({server: server});
this.socket = io.connect('http://localhost:8000'); // eslint-disable-line
frappe.db.bindSocketClient(this.socket);
@ -24,6 +26,29 @@ module.exports = {
frappe.desk = new Desk(columns);
await frappe.login();
},
setCall() {
frappe.call = async ({method, type='get', args}) => {
let url = `/api/method/${method}`;
let request = {};
if (args) {
if (type.toLowerCase()==='get') {
url += '?' + frappe.getQueryString(args);
} else {
// POST / PUT / DELETE
request.body = JSON.stringify(args);
}
}
request.headers = { 'Accept': 'application/json' };
request.method = type.toUpperCase();
let response = await fetch(url, request);
return await response.json();
}
}
};

View File

@ -20,6 +20,7 @@ module.exports = {
this.forms = {};
this.views = {};
this.flags = {};
this.methods = {};
// temp params while calling routes
this.params = {};
},
@ -46,6 +47,32 @@ module.exports = {
this.views[view][name] = module;
},
registerMethod({method, type, handler}) {
type = type.toLowerCase();
this.methods[method] = handler;
if (this.app) {
// add to router if client-server
this.app[type](`/api/method/${method}`, this.asyncHandler(async function(request, response) {
let args = {};
if (type==='get') {
args = request.query;
} else {
args = request.body;
}
const data = await handler(args);
response.json(data);
}));
}
},
call({method, type, args}) {
if (this.methods[method]) {
return this.methods[method](args);
} else {
throw `${method} not found`;
}
},
addToCache(doc) {
if (!this.docs) return;

View File

@ -48,10 +48,13 @@ module.exports = {
getQueryString(params) {
if (!params) return '';
return Object.keys(params)
.map(k => params[k] != null ? encodeURIComponent(k) + '=' + encodeURIComponent(params[k]) : null)
.filter(v => v)
.join('&');
let parts = [];
for (let key in params) {
if (key!=null && params[key]!=null) {
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
}
}
return parts.join('&');
},
asyncHandler(fn) {