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

Ember Data集成Supabase:自定义Adapter/Serializer返回空Proxy{}问题

问题分析与解决建议

核心问题在于Adapter与Serializer的类型不匹配:你使用了RESTAdapter但Serializer输出的是JSON API格式的 payload,而RESTAdapter默认期望REST格式的响应结构,导致Ember Data无法正确解析并将数据存入store。以下是具体修复步骤:


1. 将Adapter切换为JSONAPIAdapter

JSONAPIAdapter专门用于处理JSON API格式的响应,与你Serializer输出的结构匹配:

// app/adapters/application.js
import JSONAPIAdapter from '@ember-data/adapter/json-api';
import { inject as service } from '@ember/service';
import pluralize from 'ember-inflector';

export default class ApplicationAdapter extends JSONAPIAdapter {
  @service supabase;

  async findAll(store, type) {
    // 移除不必要的Promise嵌套,async函数本身返回Promise
    const { data, error } = await this.supabase.client
      .from(pluralize(type.modelName))
      .select('*');
    
    if (error) throw error;
    return data;
  }
}

2. 更新Serializer以适配JSONAPISerializer

确保Serializer继承自JSONAPISerializer,并简化normalizeResponse逻辑(直接返回JSON API格式payload即可):

// app/serializers/application.js
import JSONAPISerializer from '@ember-data/serializer/json-api';

export default class ApplicationSerializer extends JSONAPISerializer {
  normalizeResponse(store, primaryModelClass, payload) {
    return {
      data: payload.map(item => {
        // 深拷贝并移除id属性,保留其余字段作为attributes
        const attributes = { ...item };
        delete attributes.id;

        return {
          id: item.id,
          type: primaryModelClass.modelName, // 确保type为单数模型名
          attributes: attributes
        };
      })
    };
  }
}

3. 验证路由中的数据获取逻辑

确保在路由的model hook中正确使用async/await获取数据:

// app/routes/courses.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default class CoursesRoute extends Route {
  @service store;

  async model() {
    const courses = await this.store.findAll('course');
    // 可添加日志验证数据是否已存入store
    console.log('Store中的课程数据:', courses.toArray());
    return courses;
  }
}

关键修复点说明

  1. Adapter类型匹配:JSONAPIAdapter与JSONAPISerializer是配套使用的,能够正确解析你生成的JSON API格式响应。
  2. 移除冗余Promise嵌套:async函数本身会返回Promise,无需额外包裹,避免潜在的异步处理问题。
  3. 简化Serializer逻辑:直接返回符合JSON API规范的payload,让JSONAPISerializer无需额外转换即可识别。

完成以上修改后,Ember Data应该能正确将数据存入store,你可以在Ember Inspector的Data面板中看到课程模型数据,模板也能正常渲染内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:55:37