|
| 1 | +import { assert } from '@silverhand/essentials'; |
| 2 | +import { got, HTTPError } from 'got'; |
| 3 | + |
| 4 | +import type { |
| 5 | + GetConnectorConfig, |
| 6 | + SendMessageFunction, |
| 7 | + CreateConnector, |
| 8 | + SmsConnector, |
| 9 | +} from '@logto/connector-kit'; |
| 10 | +import { |
| 11 | + ConnectorError, |
| 12 | + ConnectorErrorCodes, |
| 13 | + validateConfig, |
| 14 | + ConnectorType, |
| 15 | +} from '@logto/connector-kit'; |
| 16 | + |
| 17 | +import { defaultMetadata } from './constant.js'; |
| 18 | +import { httpSmsConfigGuard } from './types.js'; |
| 19 | + |
| 20 | +const sendMessage = |
| 21 | + (getConfig: GetConnectorConfig): SendMessageFunction => |
| 22 | + async (data, inputConfig) => { |
| 23 | + const { to, type, payload } = data; |
| 24 | + const config = inputConfig ?? (await getConfig(defaultMetadata.id)); |
| 25 | + validateConfig(config, httpSmsConfigGuard); |
| 26 | + const { endpoint, authorization } = config; |
| 27 | + |
| 28 | + try { |
| 29 | + return await got.post(endpoint, { |
| 30 | + headers: { |
| 31 | + ...(authorization && { Authorization: authorization }), |
| 32 | + 'Content-Type': 'application/json', |
| 33 | + }, |
| 34 | + json: { |
| 35 | + to, |
| 36 | + type, |
| 37 | + payload, |
| 38 | + }, |
| 39 | + }); |
| 40 | + } catch (error: unknown) { |
| 41 | + if (error instanceof HTTPError) { |
| 42 | + const { |
| 43 | + response: { body: rawBody }, |
| 44 | + } = error; |
| 45 | + |
| 46 | + assert( |
| 47 | + typeof rawBody === 'string', |
| 48 | + new ConnectorError( |
| 49 | + ConnectorErrorCodes.InvalidResponse, |
| 50 | + `Invalid response raw body type: ${typeof rawBody}` |
| 51 | + ) |
| 52 | + ); |
| 53 | + |
| 54 | + throw new ConnectorError(ConnectorErrorCodes.General, rawBody); |
| 55 | + } |
| 56 | + |
| 57 | + throw new ConnectorError( |
| 58 | + ConnectorErrorCodes.General, |
| 59 | + error instanceof Error ? error.message : String(error) |
| 60 | + ); |
| 61 | + } |
| 62 | + }; |
| 63 | + |
| 64 | +const createHttpSmsConnector: CreateConnector<SmsConnector> = async ({ getConfig }) => { |
| 65 | + return { |
| 66 | + metadata: defaultMetadata, |
| 67 | + type: ConnectorType.Sms, |
| 68 | + configGuard: httpSmsConfigGuard, |
| 69 | + sendMessage: sendMessage(getConfig), |
| 70 | + }; |
| 71 | +}; |
| 72 | + |
| 73 | +export default createHttpSmsConnector; |
0 commit comments