UNPKG

@turnkey/sdk-server

Version:

JavaScript Server SDK

108 lines (105 loc) 4.13 kB
import { ApiKeyStamper } from '@turnkey/api-key-stamper'; import { TurnkeySDKClientBase } from './__generated__/sdk-client-base.mjs'; const DEFAULT_API_PROXY_ALLOWED_METHODS = [ "oauth", "createReadWriteSession", "createSubOrganization", "emailAuth", "initUserEmailRecovery", ]; class TurnkeyServerSDK { constructor(config) { this.apiClient = (apiCredentials) => { this.stamper = new ApiKeyStamper({ apiPublicKey: apiCredentials?.apiPublicKey ?? this.config.apiPublicKey, apiPrivateKey: apiCredentials?.apiPrivateKey ?? this.config.apiPrivateKey, runtimeOverride: this.config.runtimeOverride, }); return new TurnkeyApiClient({ stamper: this.stamper, apiBaseUrl: this.config.apiBaseUrl, organizationId: this.config.defaultOrganizationId, activityPoller: this.config.activityPoller, }); }; this.apiProxy = async (methodName, params) => { const apiClient = this.apiClient(); const method = apiClient[methodName]; if (typeof method === "function") { return await method(...params); } else { throw new Error(`Method: ${methodName} does not exist on TurnkeySDKClient`); } }; this.expressProxyHandler = (config) => { const allowedMethods = config.allowedMethods ?? DEFAULT_API_PROXY_ALLOWED_METHODS; return async (request, response) => { const { methodName, params } = request.body; if (!methodName || !params) { response.status(400).send("methodName and params are required."); } try { if (allowedMethods.includes(methodName)) { const result = await this.apiProxy(methodName, params); response.json(result); } else { response.status(401).send("Unauthorized proxy method"); } return; } catch (error) { if (error instanceof Error) { response.status(500).send(error.message); } else { response.status(500).send("An unexpected error occurred"); } return; } }; }; this.nextProxyHandler = (config) => { const allowedMethods = config.allowedMethods ?? DEFAULT_API_PROXY_ALLOWED_METHODS; return async (request, response) => { const { methodName, params } = request.body; if (!methodName || !params) { response.status(400).send("methodName and params are required."); } try { if (allowedMethods.includes(methodName)) { const result = await this.apiProxy(methodName, params); response.json(result); } else { response.status(401).send("Unauthorized proxy method"); } return; } catch (error) { if (error instanceof Error) { response.status(500).send(error.message); } else { response.status(500).send("An unexpected error occurred"); } return; } }; }; this.config = config; } } class TurnkeyServerClient extends TurnkeySDKClientBase { constructor(config) { super(config); } } class TurnkeyApiClient extends TurnkeyServerClient { constructor(config) { super(config); } } export { TurnkeyApiClient, TurnkeyServerClient, TurnkeyServerSDK }; //# sourceMappingURL=sdk-client.mjs.map