File size: 4,415 Bytes
31e8457
e391660
 
 
 
 
 
 
 
31e8457
 
 
 
 
 
 
 
 
 
 
 
 
 
e391660
 
 
 
 
 
 
 
 
 
31e8457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
 * Connects typed `HttpApi` clients to atoms.
 *
 * The service created here exposes the generated HTTP API client plus
 * atom-based query and mutation helpers. Query atoms call endpoints and track
 * their asynchronous result, while mutations run endpoint calls that can
 * invalidate reactivity keys after a successful request. Query atoms can also be
 * cached, serialized for hydration, and kept alive with a time-to-live.
 *
 * @since 4.0.0
 */
import * as Context from "../../Context.js";
import * as Duration from "../../Duration.js";
import * as Effect from "../../Effect.js";
import * as Layer from "../../Layer.js";
import * as Schema from "../../Schema.js";
import * as HttpClientError from "../http/HttpClientError.js";
import * as HttpApiClient from "../httpapi/HttpApiClient.js";
import * as HttpApiEndpoint from "../httpapi/HttpApiEndpoint.js";
import * as AsyncResult from "./AsyncResult.js";
import * as Atom from "./Atom.js";
import * as Reactivity from "./Reactivity.js";
/**
 * Creates a `Context.Service` class for an HTTP API client backed by an atom
 * runtime.
 *
 * **Details**
 *
 * The options provide the API definition, HTTP client layer, optional client and
 * response transforms, base URL, and runtime factory used by the query and
 * mutation helpers.
 *
 * @category constructors
 * @since 4.0.0
 */
export const Service = () => (id, options) => {
  const self = Context.Service()(id);
  const layer = Layer.effect(self, HttpApiClient.make(options.api, options));
  const runtimeFactory = options.runtime ?? Atom.runtime;
  self.runtime = runtimeFactory(typeof options.httpClient === "function" ? get => Layer.provide(layer, options.httpClient(get)) : Layer.provide(layer, options.httpClient));
  const catchErrors = Effect.catch(e => Schema.isSchemaError(e) || HttpClientError.isHttpClientError(e) ? Effect.die(e) : Effect.fail(e));
  const mutationFamily = Atom.family(({
    endpoint,
    group,
    responseMode
  }) => {
    const atom = self.runtime.fn()(Effect.fnUntraced(function* (opts) {
      const client = yield* self;
      const effect = catchErrors(client[group][endpoint]({
        ...opts,
        responseMode
      }));
      return yield* opts.reactivityKeys ? Reactivity.mutation(effect, opts.reactivityKeys) : effect;
    }));
    if (responseMode === "decoded-only") {
      const definition = options.api.groups[group].endpoints[endpoint];
      return Atom.serializable(atom, {
        key: `AtomHttpApi:mutation:${group}:${endpoint}`,
        schema: AsyncResult.Schema({
          success: Schema.Union(HttpApiEndpoint.getSuccessSchemas(definition)),
          error: Schema.Union(HttpApiEndpoint.getErrorSchemas(definition))
        })
      });
    }
    return atom;
  });
  self.mutation = (group, endpoint, options) => mutationFamily({
    group,
    endpoint,
    responseMode: options?.responseMode ?? "decoded-only"
  });
  const queryFamily = Atom.family(opts => {
    let atom = self.runtime.atom(self.use(client_ => {
      const client = client_;
      return catchErrors(client[opts.group][opts.endpoint](opts));
    }));
    if (opts.responseMode === "decoded-only" && opts.serializationKey) {
      const endpoint = options.api.groups[opts.group].endpoints[opts.endpoint];
      atom = Atom.serializable(atom, {
        key: `AtomHttpApi:${opts.group}:${opts.endpoint}:${opts.serializationKey}`,
        schema: AsyncResult.Schema({
          success: Schema.Union(HttpApiEndpoint.getSuccessSchemas(endpoint)),
          error: Schema.Union(HttpApiEndpoint.getErrorSchemas(endpoint))
        })
      });
    }
    if (opts.timeToLive) {
      atom = Duration.isFinite(opts.timeToLive) ? Atom.setIdleTTL(atom, opts.timeToLive) : Atom.keepAlive(atom);
    }
    return opts.reactivityKeys ? self.runtime.factory.withReactivity(opts.reactivityKeys)(atom) : atom;
  });
  self.query = (group, endpoint, request) => {
    const key = {
      group,
      endpoint,
      params: request.params,
      query: request.query,
      payload: request.payload,
      headers: request.headers,
      responseMode: request.responseMode ?? "decoded-only",
      reactivityKeys: request.reactivityKeys,
      timeToLive: request.timeToLive ? Duration.fromInputUnsafe(request.timeToLive) : undefined,
      serializationKey: request.serializationKey
    };
    return queryFamily(key);
  };
  return self;
};
//# sourceMappingURL=AtomHttpApi.js.map