51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
import ApplicationAdapter from './application';
|
|
import { dasherize } from '@ember/string';
|
|
|
|
export default class MealAdapter extends ApplicationAdapter {
|
|
async findRecord(store, model, id) {
|
|
let result = await fetch(`${this.host}/lookup.php?i=${id}`);
|
|
let json = await result.json();
|
|
return normalize(json.meals[0]);
|
|
}
|
|
|
|
async queryRecord(store, model, query) {
|
|
if (query === 'random') {
|
|
let result = await fetch(`${this.host}/random.php`);
|
|
let json = await result.json();
|
|
return normalize(json.meals[0]);
|
|
}
|
|
}
|
|
}
|
|
|
|
function normalize(obj) {
|
|
let attributes = {};
|
|
|
|
Object.keys(obj).forEach(key => attributes[cleanKey(key)] = obj[key]);
|
|
attributes.ingredients = groupByKeyPrefix('ingredient', attributes);
|
|
|
|
return {
|
|
data: {
|
|
type: 'meal',
|
|
id: attributes.id,
|
|
attributes,
|
|
},
|
|
};
|
|
}
|
|
|
|
function cleanKey(key) {
|
|
key = dasherize(key);
|
|
key = key.replace('str-', '');
|
|
if (key === 'id-meal') key = 'id';
|
|
if (key === 'meal') key = 'name';
|
|
return key;
|
|
}
|
|
|
|
function groupByKeyPrefix(keyPrefix, obj) {
|
|
let resultingArray = [];
|
|
Object.keys(obj).forEach(key => {
|
|
let value = obj[key];
|
|
if (!value) return;
|
|
if (key.startsWith(keyPrefix)) resultingArray.push(value);
|
|
});
|
|
return resultingArray;
|
|
}
|