Initial import of zappier-sales-pricing from zapier monorepo
This commit is contained in:
commit
0d0308b77e
7 changed files with 305 additions and 0 deletions
36
src/nats-billing.js
Normal file
36
src/nats-billing.js
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue