1
0
Fork 0
sortable-recipes/ember-ui/app/adapters/meal.js
Ava Gaiety Wroten 84a1e7d972 Backend
2019-12-24 16:52:05 -06:00

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;
}