简体   繁体   English

使用rails或ember从外部api缓存数据?

[英]Cache data from external api with rails or ember?

I have an ember/rails application with three main templates, Home, Contacts, and Payments. 我有一个带有三个主要模板的ember / rails应用程序,Home,Contacts和Payments。 Both the contacts and payments templates need an array of contacts. 联系人和付款模板都需要一系列联系人。 This array needs to be populated from an external api. 需要从外部api填充此数组。 Currently, for the contacts every time I am going to this template the external api is being hit. 目前,对于每次我要访问此模板时的联系人,外部api正在被攻击。 Ideally I would like to hit the api asynchronously when a user first signs in, grabs this data once and can refer back to it without hitting the external api until necessary. 理想情况下,我想在用户首次登录时异步点击api,抓取此数据一次,并且可以在不需要外部api的情况下返回到它。

With rails I could easily just add has_one :contacts_list for user with a postgres json column and when switching the templates conditionally refresh this whenever needed. 使用rails我可以轻松地为用户添加带有postgres json列的has_one:contacts_list,并在切换模板时有条件地在需要时刷新它。 I am curious as to the best way to deal with this problem in ember. 我很好奇在ember中处理这个问题的最佳方法。

I've used the setupController method on a route to do this type of caching. 我在路由上使用了setupController方法来执行这种类型的缓存。 Just check to see if the content is already available, and only load it if it's not there. 只需检查内容是否已经可用,只有在内容不存在时才加载。 Something like this: 像这样的东西:

App.ContactsRoute = Ember.Route.extend({
  setupController : function(controller,model){
    if(!controller.get('content')){
      this.store.find('contact').then(function(contacts){
        controller.set('content',contacts)
      });
    }
  }
});

You should create a DS.Model for 'contact' and use a has_many on Contacts and Payments model. 您应该为“联系人”创建DS.Model,并在“联系人和付款”模型上使用has_many。 Then, you could specify 'async: true' like 然后,您可以指定'async:true'之类的

DS.hasMany('contact', {async: true}),

This will load the contacts asynchronously if they have not been loaded already. 如果尚未加载联系人,它将异步加载联系人。 If they have been loaded, it will simply return the loaded contacts. 如果它们已被加载,它将只返回加载的联系人。

I am assuming that you have the following models: Contacts, Payments. 我假设您有以下型号:联系人,付款。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM