@mussnad/frappe-js-client
Version:
Next-generation TS/JS client for Frappe REST APIs, built on axios for robust, type-safe integration.
546 lines (545 loc) • 21.4 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FrappeClient = void 0;
var axios_1 = require("../utils/axios");
/**
* FrappeClient is a class that provides a client for the Frappe API.
* It is used to fetch documents from the Frappe database.
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
*/
var FrappeClient = /** @class */ (function () {
/**
* Creates a new FrappeClient instance.
*
* @param appURL - The URL of the Frappe App instance
* @param axios - The Axios instance for making HTTP requests
* @param useToken - Whether to use token based authentication
* @param token - Function that returns the authentication token
* @param tokenType - Type of token to use ('Bearer' or 'token')
*/
function FrappeClient(appURL, axios, useToken, token, tokenType) {
this.appURL = appURL;
this.axios = axios;
this.useToken = useToken !== null && useToken !== void 0 ? useToken : false;
this.token = token;
this.tokenType = tokenType !== null && tokenType !== void 0 ? tokenType : 'Bearer';
}
/**
* Fetches a list of documents from the Frappe database.
*
* @param doctype - The name of the document type to fetch
* @param args - The arguments for the fetch operation
* @returns A promise that resolves to the list of documents
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const docs = await client.getList('DocType', {
* fields: ['name', 'title'],
* })
* ```
*/
FrappeClient.prototype.getList = function (doctype, args) {
var _a;
var params = {};
if (args) {
var fields = args.fields, filters = args.filters, groupBy = args.groupBy, orderBy = args.orderBy, limit_start = args.limit_start, limit_page_length = args.limit_page_length, _b = args.asDict, asDict = _b === void 0 ? true : _b, parent_1 = args.parent, debug = args.debug, orFilters = args.orFilters;
var orderByString = orderBy ? "".concat(String(orderBy === null || orderBy === void 0 ? void 0 : orderBy.field), " ").concat((_a = orderBy === null || orderBy === void 0 ? void 0 : orderBy.order) !== null && _a !== void 0 ? _a : 'asc') : '';
params = {
fields: fields ? JSON.stringify(fields) : undefined,
filters: filters ? JSON.stringify(filters) : undefined,
group_by: groupBy,
order_by: orderByString,
limit_start: limit_start,
limit_page_length: limit_page_length,
parent: parent_1,
debug: debug,
as_dict: asDict,
or_filters: orFilters ? JSON.stringify(orFilters) : undefined,
};
}
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
url: '/api/method/frappe.client.get_list/',
params: __assign({ doctype: doctype }, params),
},
errorMessage: 'There was an error while fetching the documents.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Fetches the count of documents from the Frappe database.
*
* @param doctype - The name of the document type to fetch
* @param args - The arguments for the fetch operation
* @returns A promise that resolves to the count of documents
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const count = await client.getCount('DocType', {
* filters: ['name', '=', 'test'],
* })
* ```
*/
FrappeClient.prototype.getCount = function (doctype, args) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
url: '/api/method/frappe.client.get_count/',
params: __assign({ doctype: doctype }, args),
},
errorMessage: 'There was an error while fetching the count.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Fetches a document from the Frappe database.
*
* @param doctype - The name of the document type to fetch
* @param name - The name of the document to fetch
* @param args - The arguments for the fetch operation
* @returns A promise that resolves to the document
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const doc = await client.getDoc('DocType', 'test')
* ```
*/
FrappeClient.prototype.getDoc = function (doctype, name, args) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
url: '/api/method/frappe.client.get/',
params: __assign({ doctype: doctype, name: name }, args),
},
errorMessage: 'There was an error while fetching the document.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Fetches a value from the Frappe database.
*
* @param doctype - The name of the document type to fetch
* @param fieldname - The name of the field to fetch
* @param args - The arguments for the fetch operation
* @returns A promise that resolves to the value
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const value = await client.getValue('DocType', 'test')
* ```
*/
FrappeClient.prototype.getValue = function (doctype, fieldname, args) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
url: '/api/method/frappe.client.get_value/',
params: __assign({ doctype: doctype, fieldname: fieldname }, args),
},
errorMessage: 'There was an error while fetching the value.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Fetches a single value from the Frappe database.
*
* @param doctype - The name of the document type to fetch
* @param field - The name of the field to fetch
* @returns A promise that resolves to the value
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const value = await client.getSingleValue('DocType', 'test')
* ```
*/
FrappeClient.prototype.getSingleValue = function (doctype, field) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
url: '/api/method/frappe.client.get_single_value/',
params: { doctype: doctype, field: field },
},
errorMessage: 'There was an error while fetching the value.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Sets a value in the Frappe database.
*
* @param doctype - The name of the document type to fetch
* @param name - The name of the document to fetch
* @param fieldname - The name of the field to fetch
* @param value - The value to set
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.setValue('DocType', 'test', 'test', 'test')
* ```
*/
FrappeClient.prototype.setValue = function (doctype, name, fieldname, value) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'PUT',
url: '/api/method/frappe.client.set_value/',
params: { doctype: doctype, name: name, fieldname: fieldname, value: value },
},
errorMessage: 'There was an error while setting the value.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Inserts a document in the Frappe database.
*
* @param doc - The document to insert
* @returns A promise that resolves to the inserted document
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.insertDoc({doctype:'DocType', name:'test', fieldname:'test', value:'test'})
* ```
*/
FrappeClient.prototype.insertDoc = function (doc) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: '/api/method/frappe.client.insert/',
params: { doc: doc },
},
errorMessage: 'There was an error while inserting the document.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Inserts multiple documents in the Frappe database.
*
* @param docs - The documents to insert
* @returns A promise that resolves to the inserted documents
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.insertMany([{doctype:'DocType', name:'test', fieldname:'test', value:'test'}])
* ```
*/
FrappeClient.prototype.insertMany = function (docs) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: '/api/method/frappe.client.insert_many/',
params: { docs: docs },
},
errorMessage: 'There was an error while inserting the documents.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Saves a document in the Frappe database.
*
* @param doc - The document to save
* @returns A promise that resolves to the saved document
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.saveDoc({doctype:'DocType', name:'test', fieldname:'test', value:'test'})
* ```
*/
FrappeClient.prototype.saveDoc = function (doc) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: '/api/method/frappe.client.save/',
params: { doc: doc },
},
errorMessage: 'There was an error while saving the document.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Renames a document in the Frappe database.
*
* @param doctype - The name of the document type to rename
* @param old_name - The old name of the document
* @param new_name - The new name of the document
* @param merge - Whether to merge the document
* @returns A promise that resolves to the new document name
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const newName = await client.renameDoc('DocType', 'test', 'test2')
* ```
*/
FrappeClient.prototype.renameDoc = function (doctype, old_name, new_name, merge) {
if (merge === void 0) { merge = false; }
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: '/api/method/frappe.client.rename_doc/',
params: { doctype: doctype, old_name: old_name, new_name: new_name, merge: merge },
},
errorMessage: 'There was an error while renaming the document.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Submits a document in the Frappe database.
*
* @param doc - The document to submit
* @returns A promise that resolves to the submitted document
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.submitDoc({doctype:'DocType', name:'test', fieldname:'test', value:'test'})
* ```
*/
FrappeClient.prototype.submitDoc = function (doc) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: '/api/method/frappe.client.submit/',
params: { doc: doc },
},
errorMessage: 'There was an error while submitting the document.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Cancels a document in the Frappe database.
*
* @param doctype - The name of the document type to cancel
* @param name - The name of the document to cancel
* @returns A promise that resolves to the canceled document
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.cancelDoc('DocType', 'test')
* ```
*/
FrappeClient.prototype.cancelDoc = function (doctype, name) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: '/api/method/frappe.client.cancel/',
params: { doctype: doctype, name: name },
},
errorMessage: 'There was an error while canceling the document.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Deletes a document in the Frappe database.
*
* @param doctype - The name of the document type to delete
* @param name - The name of the document to delete
* @returns A promise that resolves to void on successful deletion
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.deleteDoc('DocType', 'test')
* ```
*/
FrappeClient.prototype.deleteDoc = function (doctype, name) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'DELETE',
url: '/api/method/frappe.client.delete/',
params: { doctype: doctype, name: name },
},
errorMessage: 'There was an error while deleting the document.',
transformResponse: function () { return void 0; },
});
};
/**
* Updates multiple documents in the Frappe database.
*
* @param docs - The documents to update
* @returns A promise that resolves to the bulk update result containing any failed documents
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* const result = await client.bulkUpdate([
* {doctype:'DocType', name:'test', fieldname:'test', value:'test'}
* ]);
* if (result.failed_docs.length > 0) {
* console.log('Some documents failed to update:', result.failed_docs);
* }
* ```
*/
FrappeClient.prototype.bulkUpdate = function (docs) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'PUT',
url: '/api/method/frappe.client.bulk_update/',
params: { docs: docs },
},
errorMessage: 'There was an error while updating the documents.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Validates a link in the Frappe database.
*
* @param doctype - The name of the document type to validate
* @param docname - The name of the document to validate
* @param fields - The fields to validate
* @returns A promise that resolves to the validated document
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* await client.validateLink('DocType', 'test', ['field1', 'field2'])
* ```
*/
FrappeClient.prototype.validateLink = function (doctype, docname, fields) {
if (fields === void 0) { fields = ['name']; }
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'GET',
url: '/api/method/frappe.client.validate_link',
params: { doctype: doctype, docname: docname, fields: JSON.stringify(fields) },
},
errorMessage: 'There was an error while validating the link.',
transformResponse: function (response) { return response.message; },
});
};
/**
* Makes a GET request to the Frappe API.
*
* @param path - The path to the API endpoint
* @param params - Optional query parameters
* @returns A promise that resolves to the complete response data
*
* @example
* ```typescript
* const client = new FrappeClient('https://instance.example.com', axiosInstance)
* // For endpoints returning {message: ...}
* const messageResponse = await client.get('/api/method/some.path');
* console.log(messageResponse.message);
*
* // For endpoints returning {data: ...}
* const dataResponse = await client.get('/api/resource/some.path');
* console.log(dataResponse.data);
* ```
*/
FrappeClient.prototype.get = function (path, params) {
var encodedParams = new URLSearchParams();
if (params) {
Object.entries(params).forEach(function (_a) {
var key = _a[0], value = _a[1];
if (value !== null && value !== undefined) {
var val = typeof value === 'object' ? JSON.stringify(value) : String(value);
encodedParams.set(key, val);
}
});
}
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'GET',
url: path,
params: encodedParams,
},
errorMessage: 'There was an error while making the GET request.',
transformResponse: function (response) { return response.data; },
});
};
/**
* Makes a POST request to the Frappe API.
*
* @param path - The path to the API endpoint
* @param data - Optional request body
* @param params - Optional query parameters
* @returns A promise that resolves to the response data
*/
FrappeClient.prototype.post = function (path, data, params) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'POST',
url: path,
data: data,
params: params,
},
errorMessage: 'There was an error while making the POST request.',
transformResponse: function (response) { return response.data; },
});
};
/**
* Makes a PUT request to the Frappe API.
*
* @param path - The path to the API endpoint
* @param data - Optional request body
* @param params - Optional query parameters
* @returns A promise that resolves to the response data
*/
FrappeClient.prototype.put = function (path, data, params) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'PUT',
url: path,
data: data,
params: params,
},
errorMessage: 'There was an error while making the PUT request.',
transformResponse: function (response) { return response.data; },
});
};
/**
* Makes a DELETE request to the Frappe API.
*
* @param path - The path to the API endpoint
* @param params - Optional query parameters
* @returns A promise that resolves to the response data
*/
FrappeClient.prototype.delete = function (path, params) {
return (0, axios_1.handleRequest)({
axios: this.axios,
config: {
method: 'DELETE',
url: path,
params: params,
},
errorMessage: 'There was an error while making the DELETE request.',
transformResponse: function (response) { return response.data; },
});
};
return FrappeClient;
}());
exports.FrappeClient = FrappeClient;