UNPKG

willwill96-petfinder-graphql

Version:

contains files and utilities to bootstrap a graphql instance wrapping the petfinder api

41 lines (40 loc) 2.19 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const node_cache_1 = __importDefault(require("node-cache")); const isomorphic_fetch_1 = __importDefault(require("isomorphic-fetch")); const fetchAccessToken = (options) => __awaiter(void 0, void 0, void 0, function* () { const params = new URLSearchParams(); params.append('grant_type', 'client_credentials'); params.append('client_id', options.petfinderApiKey); params.append('client_secret', options.petfinderSecretKey); const petfinderRes = yield (0, isomorphic_fetch_1.default)('https://api.petfinder.com/v2/oauth2/token', { method: 'POST', body: params, }); const json = yield petfinderRes.json(); return json; }); const PetfinderAccessTokenCache = new node_cache_1.default(); const TWO_MINUTES_IN_SECONDS = 60 * 2; const bufferExpiration = expirationTime => expirationTime - TWO_MINUTES_IN_SECONDS; const getAccessToken = (options) => __awaiter(void 0, void 0, void 0, function* () { const petfinderAccessToken = PetfinderAccessTokenCache.get('value'); if (petfinderAccessToken) return petfinderAccessToken; const json = yield fetchAccessToken(options); PetfinderAccessTokenCache.set('value', json.access_token, bufferExpiration(json.expires_in)); return json.access_token; }); exports.default = getAccessToken;