Skip to content

Instantly share code, notes, and snippets.

@tennox
Forked from gotjoshua/apiv3.ts
Last active November 26, 2024 13:05
Show Gist options
  • Save tennox/618072523dc91751251d55ab092a3c1b to your computer and use it in GitHub Desktop.
Save tennox/618072523dc91751251d55ab092a3c1b to your computer and use it in GitHub Desktop.
civi v3
import qs from 'npm:qs';
/*
ex:
var config = {
server:'http://example.org',
path:'/sites/all/modules/civicrm/extern/rest.php',
key:'your key from settings.civicrm.php',
api_key:'the user key'
};
*/
export class CrmAPI {
constructor(options) {
this.options = {
path: '/sites/all/modules/civicrm/extern/rest.php',
sequential: 1,
json: 1,
debug: false,
concurrency: 8, // max number of queries to run in parallel
};
Object.assign(this.options, options);
}
urlize(entity, action) {
return `${this.options.server}${this.options.path}?${qs.stringify({ entity, action })}`;
}
debug(enable) {
this.options.debug = enable || true;
}
async directcall(entity, action, params) {
let post = { ...this.options };
delete post.action;
delete post.entity;
delete post.server;
delete post.path;
delete post.concurrency;
if (typeof params === "object") {
if (Object.values(params).some(value => typeof value === "object")) {
post.json = JSON.stringify(params);
} else {
Object.assign(post, params);
}
} else {
post.id = params;
}
const uri = this.urlize(entity, action);
const debug = this.options.debug;
if (debug) console.log(`->api.${entity}.${action} ${JSON.stringify(params)}`);
try {
const response = await fetch(uri, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(post),
});
if (debug) console.log(` <-${response.status} api.${entity}.${action} ${JSON.stringify(params)}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const body = await response.json();
return body;
} catch (error) {
if (debug) console.error(error.message);
return { is_error: 1, error_message: error.message };
}
}
async call(entity, action, params) {
return this.directcall(entity, action, params);
}
get(entity, params) {
return this.call(entity, 'get', params);
}
getSingle(entity, params) {
return this.call(entity, 'getsingle', params);
}
getQuick(entity, params) {
return this.call(entity, 'getquick', params);
}
create(entity, params) {
return this.call(entity, 'create', params);
}
update(entity, params) {
return this.call(entity, 'create', params);
}
delete(entity, params) {
return this.call(entity, 'delete', params);
}
}
export const crm3 = function (options) {
return new CrmAPI(options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment