odooService.ts•2.52 kB
import * as xmlrpc from 'xmlrpc';
export type OdooConfig = {
url: string; // full URL, e.g. https://app.x-or.cloud
port: number;
db: string;
username: string;
password: string;
};
export class OdooService {
private config: OdooConfig;
private commonClient: any;
private objectClient: any;
constructor(config: OdooConfig) {
this.config = config;
// xmlrpc client for common and object endpoints
const baseUrl = new URL(config.url);
const protocol = baseUrl.protocol === 'https:' ? 'https' : 'http';
const host = baseUrl.hostname;
const commonPath = '/xmlrpc/2/common';
const objectPath = '/xmlrpc/2/object';
this.commonClient = xmlrpc.createClient({ host, port: config.port, path: commonPath, protocol });
this.objectClient = xmlrpc.createClient({ host, port: config.port, path: objectPath, protocol });
}
private callCommon(method: string, params: any[]): Promise<any> {
return new Promise((resolve, reject) => {
this.commonClient.methodCall(method, params, (err: any, value: any) => {
if (err) return reject(err);
resolve(value);
});
});
}
private callObject(model: string, method: string, params: any[]): Promise<any> {
return this.callCommon('authenticate', [this.config.db, this.config.username, this.config.password, {}])
.then((uid: number) => {
const callParams = [this.config.db, uid, this.config.password, model, method, params];
return new Promise((resolve, reject) => {
this.objectClient.methodCall('execute_kw', callParams, (err: any, value: any) => {
if (err) return reject(err);
resolve(value);
});
});
});
}
async queryLeads(domain: any[] = [], fields: string[] = ['id', 'name', 'email_from', 'phone'], limit = 50, offset = 0) {
const params = [domain, { fields, limit, offset }];
return this.callObject('crm.lead', 'search_read', params);
}
async queryCustomers(domain: any[] = [['customer_rank', '>', 0]], fields: string[] = ['id', 'name', 'email', 'phone'], limit = 50, offset = 0) {
const params = [domain, { fields, limit, offset }];
return this.callObject('res.partner', 'search_read', params);
}
async queryActivities(domain: any[] = [], fields: string[] = ['id', 'res_id', 'res_model', 'summary', 'date_deadline', 'user_id'], limit = 50, offset = 0) {
const params = [domain, { fields, limit, offset }];
return this.callObject('mail.activity', 'search_read', params);
}
}