spaps
Version:
Sweet Potato Authentication & Payment Service CLI - Docker Compose orchestrator for local Python/FastAPI SPAPS server with built-in admin middleware
81 lines (74 loc) • 2.48 kB
JavaScript
// Shared helper for thin CLI subcommands that proxy to SPAPS domain endpoints.
// Reuses auth/client.js authFetch: SPAPS_ACCESS_TOKEN env or stored creds,
// auto-refresh on 401. Domain commands focus on routing, not auth.
const { authFetch, resolveServerUrl } = require('./auth/client');
function normalizeError(err) {
if (err && err.code) return err;
const wrapped = new Error(err && err.message ? err.message : String(err));
wrapped.code = 'DOMAIN_REQUEST_FAILED';
return wrapped;
}
async function callEndpoint({ options = {}, method = 'GET', path, body = null, query = null } = {}) {
if (!path) throw new Error('callEndpoint requires a path');
const serverUrl = resolveServerUrl(options);
let fullPath = path;
if (query && typeof query === 'object') {
const params = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (v === undefined || v === null) continue;
params.append(k, String(v));
}
const qs = params.toString();
if (qs) fullPath = `${path}${path.includes('?') ? '&' : '?'}${qs}`;
}
try {
const res = await authFetch(fullPath, { serverUrl, method, body });
return {
status: res.status,
data: res.data,
raw: res.raw,
ok: res.status >= 200 && res.status < 300,
};
} catch (err) {
throw normalizeError(err);
}
}
function emit({ intent, result, isJson, successMessage = null }) {
if (isJson) {
console.log(JSON.stringify({
success: Boolean(result.ok),
command: intent,
status: result.status,
data: result.data,
}, null, 2));
return;
}
if (!result.ok) {
const msg = (result.data && (result.data.error?.message || result.data.message)) || `HTTP ${result.status}`;
console.error(`\u2717 ${intent}: ${msg}`);
return;
}
if (successMessage) {
console.log(successMessage);
}
try {
console.log(JSON.stringify(result.data, null, 2));
} catch {
console.log(String(result.data));
}
}
function emitAuthError(command, err, isJson) {
if (isJson) {
console.log(JSON.stringify({
success: false,
command,
error: { code: err.code || 'ERROR', message: err.message || String(err) },
}, null, 2));
} else {
const hint = err.code === 'NOT_AUTHENTICATED' || err.code === 'SESSION_EXPIRED'
? ' (run `spaps login` first)'
: '';
console.error(`\u2717 ${command}: ${err.message}${hint}`);
}
}
module.exports = { callEndpoint, emit, emitAuthError };