gpt4 book ai didi

javascript - 如何更有效地使用Ember中的适配器、序列化器、模型等工具?

转载 作者:行者123 更新时间:2023-12-02 21:15:04 24 4
gpt4 key购买 nike

我有一个基于Ember Data的应用。我想弄清楚如何使代码更紧凑。我的应用程序看起来像这样::有几个来自 Express 服务器的端点。在 Ember 应用程序中,每个端点对应于:适配器、序列化器、模型、路由、模板。一切都很好,但是代码太麻烦了。我是 Ember 新手,也许有一种方法可以更普遍地使用适配器和其他工具。以下是我的应用程序的一些部分,说明了它的工作原理。

localhost:5000/api/cars

localhost:5000/api/vehicles

适配器“汽车”:

import RESTAdapter from '@ember-data/adapter/rest';
export default RESTAdapter.extend({
host: http://localhost:5000/api,
pathForType() {
return "cars";
}
});

适配器“车辆”:

import RESTAdapter from '@ember-data/adapter/rest';
export default RESTAdapter.extend({
host: http://localhost:5000/api,
pathForType() {
return "vehicles";
}
});

序列化器“汽车”:

import RESTSerializer from '@ember-data/serializer/rest';
export default RESTSerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
payload = {
cars: payload
};
return this._super(store, primaryModelClass, payload, id, requestType);
},
primaryKey: '_id'
});

序列化器“车辆”:

import RESTSerializer from '@ember-data/serializer/rest';
export default RESTSerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
payload = {
vehicles: payload
};
return this._super(store, primaryModelClass, payload, id, requestType);
},
primaryKey: '_id'
});

汽车型号:

import DS from 'ember-data';
const { attr } = DS;
export default DS.Model.extend({
name: attr("string"),
body: attr("array"),
date: attr('date')
});

车辆型号(与汽车相同!):

import DS from 'ember-data';
const { attr } = DS;
export default DS.Model.extend({
name: attr("string"),
body: attr("array"),
date: attr('date')
});

汽车索引路线:

import Route from '@ember/routing/route';
export default class CarsIndexRoute extends Route {
model() {
return this.store.findAll("car");
}
}

车辆索引路线:

import Route from '@ember/routing/route';
export default class VehiclesIndexRoute extends Route {
model() {
return this.store.findAll("vehicle");
}
}

Hbs 模板完全相似。cars/index.hbs(和 cars/index.hbs):

{{#each @model as |item|}}
<h3>{{item.name}}</h3>
<p>{{item.body}}</p>
{{/each}}

代码清楚地表明,结构是相同的,差异仅在一个参数上,该参数对应于模型名称和api端点的“end”。有人能告诉我如何按照 Ember 的传统更正确地组织一切吗?谢谢!

最佳答案

Ember 的伟大之处在于它是基于约定的。在您的情况下,这意味着一旦 /cars/vehicles 位于同一端点(它们确实如此)并且具有相同的结构(它们似乎也如此),您只需一个适配器和串行器即可满足所有这些需求。

import RESTAdapter from '@ember-data/adapter/rest';

export default class ApplicationAdapter extends RESTAdapter {
host = "http://localhost:5000";
namespace = 'api'
}
import RESTSerializer from '@ember-data/serializer/rest';

export default class ApplicationSerializer extends RESTSerializer {
primaryKey = '_id';

// not sure exactly what happens in the payload but I am pretty sure you'd be able to generalize it correspondingly
}

至于模型和路线,我会保留它们原样,或者根据需要提取父类(super class)。

关于javascript - 如何更有效地使用Ember中的适配器、序列化器、模型等工具?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60993825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com