36 lines
1.2 KiB
JavaScript
36 lines
1.2 KiB
JavaScript
export const SUBJECTS = { STATEMENT_GET: 'verae.billing.statement.get' };
|
|
const PLANE = 'staff';
|
|
|
|
async function authz(subject) {
|
|
const http = process.env.AUTHZ_URL;
|
|
if (!http) return { allow: true, subject };
|
|
const r = await fetch(`${http.replace(/\/$/, '')}/check`, {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ plane: PLANE, subject }),
|
|
});
|
|
return r.json();
|
|
}
|
|
|
|
export async function billingRequest(subject, payload) {
|
|
const decision = await authz(subject);
|
|
if (decision && decision.allow === false) {
|
|
const err = new Error(decision.reason || 'denied');
|
|
err.status = 403;
|
|
throw err;
|
|
}
|
|
const url = process.env.NATS_URL;
|
|
if (!url) return null;
|
|
try {
|
|
const { connect, StringCodec } = await import('nats');
|
|
const nc = await connect({ servers: url.split(','), name: 'zappier-sales-pricing' });
|
|
const sc = StringCodec();
|
|
const m = await nc.request(subject, sc.encode(JSON.stringify({ ...payload, plane: PLANE })), { timeout: 2000 });
|
|
const out = JSON.parse(sc.decode(m.data) || '{}');
|
|
await nc.close();
|
|
return out;
|
|
} catch (err) {
|
|
if (err.status === 403) throw err;
|
|
return null;
|
|
}
|
|
}
|