Skip to content

Instantly share code, notes, and snippets.

@RandyLedbetter
Created August 25, 2018 16:44
Show Gist options
  • Save RandyLedbetter/e531e948a1c2dc318899643e413a4b54 to your computer and use it in GitHub Desktop.
Save RandyLedbetter/e531e948a1c2dc318899643e413a4b54 to your computer and use it in GitHub Desktop.
import hmacsha1 from 'hmacsha1';
import {stringify} from 'query-string';
export enum FatsecretFoodType {
Brand = 'Brand',
Generic = 'Generic',
}
export interface FatsecretFood {
food_id: string;
food_name: string;
food_type: FatsecretFoodType;
food_url: string;
brand_name?: string;
food_description?: string;
}
export interface FatsecretResponse {
foods?: {
food: FatsecretFood[];
max_results: number;
total_results: number;
page_number: number;
};
food?: FatsecretFood;
}
const API_PATH = 'https://platform.fatsecret.com/rest/server.api';
const ACCESS_KEY = 'YOUR_ACCESS_KEY';
const APP_SECRET = 'YOUR_APP_SECRET';
const OAUTH_VERSION = '1.0';
const OAUTH_SIGNATURE_METHOD = 'HMAC-SHA1';
function getOauthParameters(): object {
const timestamp = Math.round(new Date().getTime() / 1000);
return {
oauth_consumer_key: ACCESS_KEY,
oauth_nonce: `${timestamp}${Math.floor(Math.random() * 1000)}`,
oauth_signature_method: OAUTH_SIGNATURE_METHOD,
oauth_timestamp: timestamp,
oauth_version: OAUTH_VERSION,
};
}
function getSignature(queryParams: object, httpMethod = 'GET') {
const signatureBaseString = [
httpMethod,
encodeURIComponent(API_PATH),
encodeURIComponent(stringify(queryParams)),
].join('&');
const signatureKey = `${APP_SECRET}&`;
return hmacsha1(signatureKey, signatureBaseString);
}
function makeApiCall(methodParams: object, httpMethod = 'GET'): Promise<Response> {
const queryParams = {
...getOauthParameters(),
...methodParams,
format: 'json',
};
queryParams['oauth_signature'] = getSignature(queryParams, httpMethod);
return fetch(`${API_PATH}?${stringify(queryParams)}`, {method: httpMethod});
}
export async function searchFood(query: string, maxResults = 8): Promise<FatsecretResponse> {
const methodParams = {
method: 'foods.search',
max_results: maxResults,
search_expression: query,
};
const response = await makeApiCall(methodParams);
return response.json();
}
export async function getFood(foodId: string): Promise<FatsecretResponse> {
const methodParams = {
method: 'food.get',
food_id: foodId,
};
const response = await makeApiCall(methodParams);
return response.json();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment