minauth
Version:
A TypeScript library for building authentication systems on top of the Mina blockchain and other zero-knowledge proofs solutions.
59 lines • 2.53 kB
JavaScript
import * as z from 'zod';
const defaultPluginRouterFetchOpts = {
isPluginRouteFetch: true
};
export class PluginRouter {
constructor(logger, serverUrl, pluginName, customRouteMapping) {
this.logger = logger;
this.serverUrl = serverUrl;
this.pluginName = pluginName;
this.customRouteMapping = customRouteMapping;
}
static async initialize(logger, serverUrl, pluginName, activePluginsRoute = '/plugins/activePlugins', customRouteMapping) {
const activePluginsResp = (await fetch(`${serverUrl}${activePluginsRoute}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
})).json();
const activePlugins = z.array(z.string()).parse(await activePluginsResp);
if (!activePlugins.includes(pluginName)) {
throw new Error(`Plugin ${pluginName} is not active. Active plugins: ${activePlugins}`);
}
return new PluginRouter(logger, serverUrl, pluginName, customRouteMapping);
}
async request(method, pluginRoute, schema, body, pluginRouteFetchOpts = defaultPluginRouterFetchOpts) {
try {
const pluginPath = pluginRouteFetchOpts.isPluginRouteFetch
? `/plugins/${this.pluginName}`
: '';
const url = this.customRouteMapping
? this.customRouteMapping(pluginRoute)
: `${this.serverUrl}${pluginPath}${pluginRoute}`;
this.logger.debug(`Requesting ${method} ${pluginRoute}`);
const response = await fetch(`${url}`, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: method === 'POST' ? JSON.stringify(body) : null
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
const validationResult = schema.safeParse(data);
if (!validationResult.success) {
throw new Error('Validation failed');
}
return validationResult.data;
}
catch (error) {
this.logger.error('Error in fetch operation:', error);
throw error;
}
}
async get(pluginRoute, schema) {
return this.request('GET', pluginRoute, schema);
}
async post(pluginRoute, schema, value) {
this.request('POST', pluginRoute, schema, value);
}
}
//# sourceMappingURL=pluginrouter.js.map