sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ Speech/ BindingHttp.ts

import * as Effect from "effect/Effect";
import * as GCPBindings from "../GCPBindings.ts";
import { grantFor, type BindingIam, type GcpHttpOp } from "../HttpBinding.ts";
import type { CustomClass } from "./CustomClass.ts";
import type { PhraseSet } from "./PhraseSet.ts";

const makeNamedHttpBinding = <
  Resource extends CustomClass | PhraseSet,
  I,
  A,
  E,
  Req = void,
>(options: {
  tag: string;
  iam: BindingIam;
  operation: GcpHttpOp<I, A, E>;
  toInput: (name: string, request: Req | undefined) => I;
}) =>
  Effect.gen(function* () {
    const bind = yield* GCPBindings.Bind;
    const run = yield* GCPBindings.withCredentials(options.operation);
    return Effect.fn(function* (resource: Resource) {
      if (!globalThis.__ALCHEMY_RUNTIME__) {
        yield* bind`${options.tag}(${resource})`({
          iam: [grantFor(options.iam, resource.name)],
        });
      }
      const name = yield* resource.name;
      return Effect.fn(`${options.tag}(${resource.LogicalId})`)(function* (request?: Req) {
        const resourceName = yield* name;
        return yield* run(options.toInput(resourceName, request));
      });
    });
  });

/**
 * Shared HTTP scaffolding for Speech-to-Text bindings.
 * NOT exported from index.ts.
 */
export const makeCustomClassHttpBinding = <I, A, E, Req = void>(options: {
  tag: string;
  iam: BindingIam;
  operation: GcpHttpOp<I, A, E>;
  toInput: (name: string, request: Req | undefined) => I;
}) => makeNamedHttpBinding<CustomClass, I, A, E, Req>(options);

export const makePhraseSetHttpBinding = <I, A, E, Req = void>(options: {
  tag: string;
  iam: BindingIam;
  operation: GcpHttpOp<I, A, E>;
  toInput: (name: string, request: Req | undefined) => I;
}) => makeNamedHttpBinding<PhraseSet, I, A, E, Req>(options);