@settlemint/sdk-hasura
Version:
Hasura and PostgreSQL integration module for SettleMint SDK, enabling database operations and GraphQL queries
266 lines (262 loc) • 9 kB
JavaScript
/* SettleMint Hasura SDK - GraphQL API */
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
const __settlemint_sdk_utils = __toESM(require("@settlemint/sdk-utils"));
const __settlemint_sdk_utils_http = __toESM(require("@settlemint/sdk-utils/http"));
const __settlemint_sdk_utils_logging = __toESM(require("@settlemint/sdk-utils/logging"));
const __settlemint_sdk_utils_runtime = __toESM(require("@settlemint/sdk-utils/runtime"));
const __settlemint_sdk_utils_validation = __toESM(require("@settlemint/sdk-utils/validation"));
const gql_tada = __toESM(require("gql.tada"));
const graphql_request = __toESM(require("graphql-request"));
const zod = __toESM(require("zod"));
//#region src/utils/track-all-tables.ts
/**
* Track all tables in a database
*
* @param databaseName - The name of the database to track tables for
* @param client - The client options to use for the Hasura client
* @param tableOptions - The options to use for the table tracking
* @param tableOptions.includeSchemas - The schemas to include in the tracking
* @param tableOptions.excludeSchemas - The schemas to exclude from the tracking
* @returns A promise that resolves to an object with a result property indicating success or failure
* @example
* import { trackAllTables } from "@settlemint/sdk-hasura/utils/track-all-tables";
*
* const client = createHasuraMetadataClient({
* instance: "http://localhost:8080",
* accessToken: "test",
* adminSecret: "test",
* });
*
* const result = await trackAllTables("default", client, {
* excludeSchemas: ["drizzle"],
* });
* if (result.result === "success") {
* console.log("Tables tracked successfully");
* } else {
* console.error("Failed to track tables");
* }
*/
async function trackAllTables(databaseName, client, tableOptions = {
includeSchemas: undefined,
excludeSchemas: undefined
}) {
const messages = [];
const { includeSchemas, excludeSchemas } = tableOptions;
const getTablesResult = await client({
type: "pg_get_source_tables",
args: { source: databaseName }
});
if (!getTablesResult.ok) {
throw new Error(`Failed to get tables: ${JSON.stringify(getTablesResult.data)}`);
}
const tables = getTablesResult.data;
if (tables.length === 0) {
return {
result: "no-tables",
messages
};
}
messages.push(`Found ${tables.length} tables in database "${databaseName}"`);
await client({
type: "pg_untrack_tables",
args: {
tables: tables.map((table) => ({ table })),
allow_warnings: true
}
});
const tablesToTrack = tables.filter((table) => {
if (Array.isArray(includeSchemas)) {
return includeSchemas.includes(table.schema);
}
if (Array.isArray(excludeSchemas)) {
return !excludeSchemas.includes(table.schema);
}
return true;
});
const trackResult = await client({
type: "pg_track_tables",
args: {
tables: tablesToTrack.map((table) => ({ table })),
allow_warnings: true
}
});
if (!trackResult.ok) {
throw new Error(`Failed to track tables: ${JSON.stringify(trackResult.data)}`);
}
messages.push(`Successfully tracked ${tablesToTrack.length} tables`);
return {
result: "success",
messages
};
}
//#endregion
//#region src/hasura.ts
/**
* Schema for validating client options for the Hasura client.
*/
const ClientOptionsSchema = zod.z.object({
instance: __settlemint_sdk_utils_validation.UrlOrPathSchema,
accessToken: __settlemint_sdk_utils_validation.ApplicationAccessTokenSchema.optional(),
adminSecret: zod.z.string(),
cache: zod.z.enum([
"default",
"force-cache",
"no-cache",
"no-store",
"only-if-cached",
"reload"
]).optional()
});
/**
* Creates a Hasura GraphQL client with proper type safety using gql.tada
*
* @param options - Configuration options for the client
* @param clientOptions - Optional GraphQL client configuration options
* @param logger - Optional logger to use for logging the requests
* @returns An object containing:
* - client: The configured GraphQL client instance
* - graphql: The initialized gql.tada function for type-safe queries
* @throws Will throw an error if the options fail validation against ClientOptionsSchema
* @example
* import { createHasuraClient } from '@settlemint/sdk-hasura';
* import type { introspection } from "@schemas/hasura-env";
* import { createLogger, requestLogger } from "@settlemint/sdk-utils/logging";
*
* const logger = createLogger();
*
* const { client, graphql } = createHasuraClient<{
* introspection: introspection;
* disableMasking: true;
* scalars: {
* timestamp: string;
* timestampz: string;
* uuid: string;
* date: string;
* time: string;
* jsonb: string;
* numeric: string;
* interval: string;
* geometry: string;
* geography: string;
* };
* }>({
* instance: process.env.SETTLEMINT_HASURA_ENDPOINT,
* accessToken: process.env.SETTLEMINT_ACCESS_TOKEN,
* adminSecret: process.env.SETTLEMINT_HASURA_ADMIN_SECRET,
* }, {
* fetch: requestLogger(logger, "hasura", fetch) as typeof fetch,
* });
*
* // Making GraphQL queries
* const query = graphql(`
* query GetUsers {
* users {
* id
* name
* email
* }
* }
* `);
*
* const result = await client.request(query);
*/
function createHasuraClient(options, clientOptions, logger) {
(0, __settlemint_sdk_utils_runtime.ensureServer)();
const validatedOptions = (0, __settlemint_sdk_utils_validation.validate)(ClientOptionsSchema, options);
const graphql = (0, gql_tada.initGraphQLTada)();
const fullUrl = new URL(validatedOptions.instance).toString();
return {
client: new graphql_request.GraphQLClient(fullUrl, {
...clientOptions,
headers: (0, __settlemint_sdk_utils_http.appendHeaders)(clientOptions?.headers, {
"x-auth-token": validatedOptions.accessToken,
"x-hasura-admin-secret": validatedOptions.adminSecret
}),
fetch: logger ? (0, __settlemint_sdk_utils_logging.requestLogger)(logger, "hasura", fetch) : fetch
}),
graphql
};
}
/**
* Creates a Hasura Metadata client
*
* @param options - Configuration options for the client
* @param logger - Optional logger to use for logging the requests
* @returns A function that can be used to make requests to the Hasura Metadata API
* @throws Will throw an error if the options fail validation against ClientOptionsSchema
* @example
* import { createHasuraMetadataClient } from '@settlemint/sdk-hasura';
*
* const client = createHasuraMetadataClient({
* instance: process.env.SETTLEMINT_HASURA_ENDPOINT,
* accessToken: process.env.SETTLEMINT_ACCESS_TOKEN,
* adminSecret: process.env.SETTLEMINT_HASURA_ADMIN_SECRET,
* });
*
* const result = await client({
* type: "pg_get_source_tables",
* args: {
* source: "default",
* },
* });
*/
function createHasuraMetadataClient(options, logger) {
(0, __settlemint_sdk_utils_runtime.ensureServer)();
const validatedOptions = (0, __settlemint_sdk_utils_validation.validate)(ClientOptionsSchema, options);
const baseUrl = (0, __settlemint_sdk_utils.extractBaseUrlBeforeSegment)(options.instance, "/v1/graphql");
const queryEndpoint = new URL(`${baseUrl}/v1/metadata`).toString();
const fetchInstance = logger ? (0, __settlemint_sdk_utils_logging.requestLogger)(logger, "hasura", fetch) : fetch;
return async (query) => {
const response = await fetchInstance(queryEndpoint, {
method: "POST",
headers: (0, __settlemint_sdk_utils_http.appendHeaders)({ "Content-Type": "application/json" }, {
"x-auth-token": validatedOptions.accessToken,
"x-hasura-admin-secret": validatedOptions.adminSecret
}),
body: JSON.stringify(query)
});
if (!response.ok) {
return {
ok: false,
data: await response.json()
};
}
return {
ok: true,
data: await response.json()
};
};
}
//#endregion
exports.ClientOptionsSchema = ClientOptionsSchema;
exports.createHasuraClient = createHasuraClient;
exports.createHasuraMetadataClient = createHasuraMetadataClient;
Object.defineProperty(exports, 'readFragment', {
enumerable: true,
get: function () {
return gql_tada.readFragment;
}
});
exports.trackAllTables = trackAllTables;
//# sourceMappingURL=hasura.cjs.map