帮助和配置文件
助手和配置文件是软件开发中的重要组成部分,它们有助于组织代码、管理设置以及简化重复性任务。
- 首先我们创建一个关于辅助的配置文件
- 例如我们的API URL,在程序中请求一般不止一次,而且如果URL有变动我们需要修改多个地方,我们可以创建一个单独的JS用来简化重复性任务;
export const API_URL = 'https://forkify-api.herokuapp.com/api/v2/recipes';
- 之后需要在model中进行引用
import { API_URL } from './config.js';
- 接着就将URL进行变量替换了
const res = await fetch(`${API_URL}/${id}`);
- 配置文件先这样,创建一个帮助的文件
export const getJSON = async function (url) {try {const res = await fetch(url);const data = await res.json();if (!res.ok) throw new Error(`${data.message} (${res.status})`);return data;} catch (err) {console.log(err);}
};
- 将请求放入单独的文件后,我们依然在model中引入一下,然后将重复性代码进行更换
import { getJSON } from './helpers.js';export const loadRecipe = async function (id) {try {const data = await getJSON(`${API_URL}/${id}`);const { recipe } = data.data;state.recipe = {id: recipe.id,title: recipe.title,publisher: recipe.publisher,sourceUrl: recipe.source_url,image: recipe.image_url,servings: recipe.servings,cookingTime: recipe.cooking_time,ingredients: recipe.ingredients,};console.log(state.recipe);} catch (err) {console.error(`${err}😰😰😰`);}
};
- 这样我们基本上就完成了辅助和配置的文件,但是我们还要为getJSON函数加上一些定时之类的,让其变得更加的健壮,事件在控制器中写过,我们直接复制过来就好;
const timeout = function (s) {return new Promise(function (_, reject) {setTimeout(function () {reject(new Error(`Request took too long! Timeout after ${s} second`));}, s * 1000);});
};export const getJSON = async function (url) {try {const res = await Promise.race([fetch(url), timeout(5)]);const data = await res.json();if (!res.ok) throw new Error(`${data.message} (${res.status})`);return data;} catch (err) {throw err;}
};
- 所以配置文件我们将一些配置项放入里面,以便更好的扩展和维护,比如将超时的时间也放入配置的文件中
export const TIMEOUT_SEC = 10;
import { TIMEOUT_SEC } from './config.js';
export const getJSON = async function (url) {try {const res = await Promise.race([fetch(url), timeout(TIMEOUT_SEC)]);const data = await res.json();if (!res.ok) throw new Error(`${data.message} (${res.status})`);return data;} catch (err) {throw err;}
};