Skip to content

Commit

Permalink
feat(src): adds rapid api support using new fields: rapidApiKey and r…
Browse files Browse the repository at this point in the history
…apidApiHost
  • Loading branch information
KenEucker committed Jan 5, 2022
1 parent 17d6e70 commit 8258321
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 19 deletions.
1 change: 1 addition & 0 deletions example/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const imgur = new ImgurClient({
const run = async (client) => {

await getAuthorizationHeader(client).then(console.log)
console.log(client.credentials)

const imageStream = createReadStream(join(__dirname, 'small.jpg'));
const videoStream = createReadStream(join(__dirname, 'small.mp4'));
Expand Down
23 changes: 19 additions & 4 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import {
SearchGalleryOptions,
} from './gallery';
import { getAlbum } from './album';
import { getAlbums, getAlbumsIds } from './account';
import { getAccount, getAlbums, getAlbumsIds } from './account';
import { IMGUR_API_PREFIX } from './common/endpoints';
import {
AccountData,
AlbumData,
Credentials,
GalleryData,
Expand All @@ -31,14 +32,17 @@ import {
const USERAGENT = 'imgur (https://github.com/keneucker/imgur)';

import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';

export type { Credentials as ImgurCredentials, ImgurApiResponse };
export class ImgurClient extends EventEmitter {
private plainFetcher: AxiosInstance;
private fetcher: AxiosInstance;

constructor(readonly credentials: Credentials) {
constructor(public credentials: Credentials) {
super();

this.credentials.rapidApiHost = credentials.rapidApiKey?.length
? credentials.rapidApiHost ?? 'imgur-apiv3.p.rapidapi.com'
: credentials.rapidApiHost;
const headers =
typeof window !== 'undefined'
? {}
Expand All @@ -52,14 +56,21 @@ export class ImgurClient extends EventEmitter {
responseType: 'json',
});
this.fetcher = axios.create({
baseURL: IMGUR_API_PREFIX,
baseURL: credentials.rapidApiKey?.length
? `https://${this.credentials.rapidApiHost}`
: IMGUR_API_PREFIX,
headers,
responseType: 'json',
});
this.fetcher.interceptors.request.use(
async (config: AxiosRequestConfig) => {
config.headers = config.headers ? config.headers : {};
config.headers.authorization = await getAuthorizationHeader(this);

if (credentials.rapidApiKey?.length) {
config.headers['x-rapidapi-host'] = credentials.rapidApiHost;
config.headers['x-rapidapi-key'] = credentials.rapidApiKey;
}
return config;
},
(e: Error) => Promise.reject(e)
Expand All @@ -86,6 +97,10 @@ export class ImgurClient extends EventEmitter {
return getAlbum(this, albumHash);
}

getAccount(account: string): Promise<ImgurApiResponse<AccountData>> {
return getAccount(this, account);
}

getAlbums(
account: string,
page?: number
Expand Down
19 changes: 16 additions & 3 deletions src/common/types.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
export interface AccessToken {
accessToken: string;
accessToken?: string;
refreshToken?: string;
}

export interface RapidApiKey {
rapidApiHost?: string;
rapidApiKey?: string;
}

export interface ClientId {
clientId: string;
clientId?: string;
clientSecret?: string;
}

export type Credentials = AccessToken | ClientId;
export interface Credentials extends AccessToken, ClientId, RapidApiKey {}

export interface ImgurTokenResponse {
account_username?: string;
access_token: string;
refresh_token: string;
token_type?: string;
expires_in?: number;
}

export function isAccessToken(arg: unknown): arg is AccessToken {
return (arg as AccessToken).accessToken !== undefined;
Expand Down
12 changes: 9 additions & 3 deletions src/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,11 @@ export function getImgurApiResponseFromResponse(
const getResponseData = (d) =>
Array.isArray(d) ? d.map((t) => (responseIsError ? t.detail : t.data)) : d;

if (typeof response === 'string') {
if (typeof response === 'undefined') {
data = 'response was empty';
status = 500;
success = false;
} else if (typeof response === 'string') {
data = response as string;
status = 500;
success = false;
Expand All @@ -70,8 +74,10 @@ export function getImgurApiResponseFromResponse(
response.data.status;
data = getResponseData(
responseIsError
? response.data.errors ?? response.data.data.error.message
: response.data.data ?? response.data
? response.data.errors ??
response.data.data.error.message ??
response.data.data.error
: response.data.data ?? response.data.message ?? response.data
);
}

Expand Down
18 changes: 9 additions & 9 deletions src/getAuthorizationHeader.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import {
AccessToken,
isAccessToken,
isRefreshToken,
isClientId,
ImgurTokenResponse,
Credentials,
} from './common/types';
import { ImgurClient } from './client';
import { IMGUR_API_PREFIX, TOKEN_ENDPOINT } from './common/endpoints';
Expand All @@ -14,8 +15,9 @@ export async function getAuthorizationHeader(
return `Bearer ${client.credentials.accessToken}`;
}

const { clientId, clientSecret, refreshToken } = client.credentials;

if (isRefreshToken(client.credentials)) {
const { clientId, clientSecret, refreshToken } = client.credentials;
const options: Record<string, unknown> = {
url: TOKEN_ENDPOINT,
baseURL: IMGUR_API_PREFIX,
Expand All @@ -28,22 +30,20 @@ export async function getAuthorizationHeader(
},
};
const response = await client.plainRequest(options);
const authorization: any = response.data;

if (response.status === 200 && authorization) {
if (response.status === 200 && response.data) {
const { access_token: accessToken, refresh_token: refreshToken } =
authorization;
response.data as ImgurTokenResponse;

(client.credentials as unknown as AccessToken).accessToken = accessToken;
(client.credentials as unknown as AccessToken).refreshToken =
refreshToken;
(client.credentials as Credentials).accessToken = accessToken;
(client.credentials as Credentials).refreshToken = refreshToken;

return `Bearer ${accessToken}`;
}
}

if (isClientId(client.credentials)) {
return `Client-ID ${client.credentials.clientId}`;
return `Client-ID ${clientId}`;
}

return null;
Expand Down

0 comments on commit 8258321

Please sign in to comment.