You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于SWAPI的多类别通用请求实现及重复代码优化技术问询

Handling SWAPI Requests & Refactoring Repetitive Code

Great question! Let’s break this down into two clear parts to tackle both your universal request needs and code duplication problem.


1. Building a Universal Request Handler for SWAPI’s Heroes, Planets, and Starships

First, let’s clarify: SWAPI exposes heroes under the people endpoint, planets under planets, and starships under starships. To make a universal request function that works for all three (and any other SWAPI resource), we can abstract the resource type and dynamic query parameters into reusable logic.

Here’s a practical, adaptable approach (we’ll use JavaScript with fetch for concrete examples, but you can mirror this pattern in Python, Java, or any language):

Universal Request Function

async function fetchSWAPIResource(resourceType, queryParams = {}) {
  // Convert query parameters into a valid URL search string
  const searchParams = new URLSearchParams(queryParams);
  const baseUrl = `https://swapi.co/api/${resourceType}/`;
  const fullUrl = `${baseUrl}?${searchParams.toString()}`;

  try {
    const response = await fetch(fullUrl);
    if (!response.ok) throw new Error(`Request failed with status: ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error(`Failed to fetch ${resourceType} data:`, error);
    throw error; // Re-throw so the caller can handle errors as needed
  }
}

How to Use It for Each Resource

  • Heroes (people): Fetch Luke Skywalker with specific hair color
    fetchSWAPIResource('people', { name: 'Luke Skywalker', hair_color: 'blond' });
    
  • Planets: Fetch all arid planets
    fetchSWAPIResource('planets', { climate: 'arid' });
    
  • Starships: Fetch all X-wing model starships
    fetchSWAPIResource('starships', { model: 'T-65 X-wing' });
    

This function works for any SWAPI resource because it:

  • Accepts the resource type as a flexible parameter
  • Dynamically builds the query string from any key-value pairs you pass
  • Includes consistent error handling across all requests

2. Refactoring Repetitive Query Logic

You mentioned your three query functions have identical structure—only variable names and one unique property differ. Let’s fix that with DRY (Don’t Repeat Yourself) principles.

Example of Repetitive Code (What You Might Have Now)

// Original repetitive code
async function fetchHeroByName(name) {
  const url = `https://swapi.co/api/people/?name=${name}`;
  const res = await fetch(url);
  return res.json();
}

async function fetchPlanetByName(name) {
  const url = `https://swapi.co/api/planets/?name=${name}`;
  const res = await fetch(url);
  return res.json();
}

async function fetchStarshipByName(name) {
  const url = `https://swapi.co/api/starships/?name=${name}`;
  const res = await fetch(url);
  return res.json();
}

Refactored Solution

Since all three functions share the same core logic (fetch by name parameter, just different resource types), we can wrap this into a single reusable function—even better, build on the universal request handler we created earlier:

// Refactored function to replace all three repetitive ones
async function fetchSWAPIResourceByName(resourceType, name) {
  return fetchSWAPIResource(resourceType, { name });
}

Usage for Each Resource

// Fetch a hero
fetchSWAPIResourceByName('people', 'Luke Skywalker');
// Fetch a planet
fetchSWAPIResourceByName('planets', 'Tatooine');
// Fetch a starship
fetchSWAPIResourceByName('starships', 'X-wing');

If You Have One Shared + One Unique Property

If your queries each have one shared property (e.g., name) plus one unique property (e.g., hair_color for heroes, climate for planets, model for starships), we can extend this further:

async function fetchSWAPIResourceWithSharedAndUnique(resourceType, sharedName, uniqueParamKey, uniqueParamValue) {
  const queryParams = {
    name: sharedName,
    [uniqueParamKey]: uniqueParamValue
  };
  return fetchSWAPIResource(resourceType, queryParams);
}

// Usage examples:
fetchSWAPIResourceWithSharedAndUnique('people', 'Luke Skywalker', 'hair_color', 'blond');
fetchSWAPIResourceWithSharedAndUnique('planets', 'Tatooine', 'climate', 'arid');
fetchSWAPIResourceWithSharedAndUnique('starships', 'X-wing', 'model', 'T-65 X-wing');

Why This Works

  • Eliminates redundant code: No more copying/pasting request logic for each resource
  • Easier maintenance: If you need to update error handling, add caching, or change the base URL, you only modify one function
  • Clearer readability: Anyone looking at the code can immediately see the pattern and how each resource is fetched

内容的提问来源于stack exchange,提问作者Igor Shvets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:11:46