| 184 | const customersGetUrl = `${(env.AUTUMN_API_URL || AUTUMN_DEFAULT_URL).replace(/\/+$/, "")}/v1/customers.get`; |
| 185 | |
| 186 | const findCustomer = (organizationId: string) => |
| 187 | Effect.gen(function* () { |
| 188 | yield* Effect.annotateCurrentSpan({ "autumn.customer.id": organizationId }); |
| 189 | const failed = (message: string, cause?: unknown) => new AutumnError({ message, cause }); |
| 190 | const response = yield* Effect.tryPromise({ |
| 191 | try: (signal) => |
| 192 | fetch(customersGetUrl, { |
| 193 | method: "POST", |
| 194 | headers: { |
| 195 | authorization: `Bearer ${secretKey}`, |
| 196 | accept: "application/json", |
| 197 | "content-type": "application/json", |
| 198 | "x-api-version": AUTUMN_API_VERSION, |
| 199 | }, |
| 200 | body: JSON.stringify({ customer_id: organizationId }), |
| 201 | signal, |
| 202 | }), |
| 203 | catch: (cause) => failed("Autumn customer lookup failed", cause), |
| 204 | }); |
| 205 | yield* Effect.annotateCurrentSpan({ "http.response.status_code": response.status }); |
| 206 | if (response.status !== 200 && response.status !== 404) { |
| 207 | return yield* failed(`Autumn customer lookup answered ${response.status}`, { |
| 208 | statusCode: response.status, |
| 209 | }); |
| 210 | } |
| 211 | const body = yield* Effect.tryPromise({ |
| 212 | try: (): Promise<unknown> => response.json(), |
| 213 | catch: (cause) => failed("Autumn customer lookup returned invalid JSON", cause), |
| 214 | }); |
| 215 | if (response.status === 404) { |
| 216 | // Only Autumn's own code means "no customer"; any other 404, such as |
| 217 | // an unknown route, is a failure. |
| 218 | const missing = Option.exists( |
| 219 | decodeErrorBody(body), |
| 220 | (error) => error.code === CUSTOMER_NOT_FOUND_CODE, |
| 221 | ); |
| 222 | if (missing) return null; |
| 223 | return yield* failed("Autumn customer lookup answered 404", { statusCode: 404 }); |
| 224 | } |
| 225 | const customer = decodeCustomerBody(body); |
| 226 | if (Option.isNone(customer)) { |
| 227 | return yield* failed("Autumn customer lookup returned an unexpected body"); |
| 228 | } |
| 229 | return { |
| 230 | subscriptions: customer.value.subscriptions.map((subscription) => ({ |
| 231 | planId: subscription.plan_id, |
| 232 | status: subscription.status, |
| 233 | })), |
| 234 | }; |
| 235 | }).pipe(Effect.withSpan("autumn.findCustomer")); |
| 236 | |
| 237 | /** |
| 238 | * Run `operation`; if Autumn answers "no such customer", provision the |