| 44 | }; |
| 45 | |
| 46 | class PipedriveCrmService implements CRM { |
| 47 | private credential: CredentialPayload; |
| 48 | private log: typeof logger; |
| 49 | private auth: OAuthManager; |
| 50 | private apiDomain: string; |
| 51 | |
| 52 | constructor(credential: CredentialPayload) { |
| 53 | this.credential = credential; |
| 54 | this.log = logger.getSubLogger({ prefix: [`[[lib] ${appConfig.slug}`] }); |
| 55 | |
| 56 | const tokenResponse = getTokenObjectFromCredential(credential); |
| 57 | // Pipedrive stores api_domain in the token object |
| 58 | const key = credential.key as { api_domain?: string }; |
| 59 | this.apiDomain = key.api_domain || ""; |
| 60 | |
| 61 | this.auth = new OAuthManager({ |
| 62 | credentialSyncVariables: { |
| 63 | APP_CREDENTIAL_SHARING_ENABLED: APP_CREDENTIAL_SHARING_ENABLED, |
| 64 | CREDENTIAL_SYNC_ENDPOINT: CREDENTIAL_SYNC_ENDPOINT, |
| 65 | CREDENTIAL_SYNC_SECRET: CREDENTIAL_SYNC_SECRET, |
| 66 | CREDENTIAL_SYNC_SECRET_HEADER_NAME: CREDENTIAL_SYNC_SECRET_HEADER_NAME, |
| 67 | }, |
| 68 | resourceOwner: { |
| 69 | type: credential.teamId ? "team" : "user", |
| 70 | id: credential.teamId ?? credential.userId, |
| 71 | }, |
| 72 | appSlug: appConfig.slug, |
| 73 | currentTokenObject: tokenResponse, |
| 74 | fetchNewTokenObject: async ({ refreshToken }: { refreshToken: string | null }) => { |
| 75 | if (!refreshToken) { |
| 76 | return null; |
| 77 | } |
| 78 | const { client_id, client_secret } = await getPipedriveAppKeys(); |
| 79 | const authHeader = `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString("base64")}`; |
| 80 | return fetch("https://oauth.pipedrive.com/oauth/token", { |
| 81 | method: "POST", |
| 82 | headers: { |
| 83 | Authorization: authHeader, |
| 84 | "Content-Type": "application/x-www-form-urlencoded", |
| 85 | }, |
| 86 | body: new URLSearchParams({ |
| 87 | grant_type: "refresh_token", |
| 88 | refresh_token: refreshToken, |
| 89 | }), |
| 90 | }); |
| 91 | }, |
| 92 | isTokenObjectUnusable: async function (response) { |
| 93 | const myLog = logger.getSubLogger({ prefix: ["pipedrive-crm:isTokenObjectUnusable"] }); |
| 94 | myLog.debug(safeStringify({ status: response.status, ok: response.ok })); |
| 95 | if (!response.ok) { |
| 96 | let responseBody; |
| 97 | try { |
| 98 | responseBody = await response.clone().json(); |
| 99 | } catch { |
| 100 | return null; |
| 101 | } |
| 102 | myLog.debug(safeStringify({ responseBody })); |
| 103 | // Pipedrive returns "invalid_grant" when refresh token is invalid |
nothing calls this directly
no test coverage detected