Ember.js with Cloudkit JS

Ember.js with Cloudkit JS

本文关键字:JS Cloudkit with js Ember      更新时间:2023-09-26

我已经使用CloudKit JS构建了一个小型原型项目,现在开始构建它的下一个版本,并且我想使用Ember,因为我有一些基本的经验。但是,我不太确定将CloudKit JS代码放在哪里。例如,我应该在哪里添加配置部分和身份验证功能?我认为一旦我找到了身份验证代码的位置,我就可以将我的一些查询函数添加到各个视图和组件中,对吗?

这是我的配置代码(删除了容器和 id):

CloudKit.configure({
containers: [{
  containerIdentifier: '###',
  // @todo Must generate a production token for app store version
  apiToken: '###',
  auth: {
    persist: true
  },
  // @todo Must switch to production for app store version
  environment: 'development'
}]
});

这是身份验证函数:

function setupAuth() {
  // Get the container.
  var container = CloudKit.getDefaultContainer();
  //Function to call when user logs in
  function gotoAuthenticatedState( userInfo ) {
    // Checks if user allows us to look up name
    var userName = '';
    if ( userInfo.isDiscoverable ) {
      userName = userInfo.firstName + ' ' + userInfo.lastName;
    } else {
      userName = 'User record name: ' + userInfo.userRecordName;
    }
    //Calls out initialization function
    init();
    //Sets up UI for logged in users
    setAuthenticatedUI( userName );
    //Register logged out function
     container
      .whenUserSignsOut()
      .then( gotoUnauthenticatedState );
  }
  //Function to call when user logs out
  function gotoUnauthenticatedState( error ) {
    //Checks if error occurred
    if ( error && error.ckErrorCode === 'AUTH_PERSIST_ERROR' ) {
      displayError( logOutError, 'Error code: AUTH_PERSIST_ERROR' );
    }
    // Sets up the UI for logged out users
    setUnauthenticatedUI();
    //Register logged in function
    container
      .whenUserSignsIn()
      .then( gotoAuthenticatedState )
      .catch( gotoUnauthenticatedState );
  }
  // Check a user is signed in and render the appropriate button.
  return container.setUpAuth()
    .then( function( userInfo ) {
      // userInfo is the signed-in user or null.
      if ( userInfo ) {
        gotoAuthenticatedState( userInfo );
      } else {
        gotoUnauthenticatedState();
      }
    });
}

然后,init() 调用函数来设置查询,以使用记录将图表添加到页面。setAuthenticatedUI() 和 setUnauthenticatedUI() 函数只是在用户通过身份验证后应用和删除类。

答案很大程度上取决于您正在使用的 Ember 版本以及您是否计划如何使用它。有路线?简单的路线?路由处理程序?

例如,如果您使用的是 Ember v2.3.0,则可以考虑使用依赖项注入 (https://guides.emberjs.com/v2.3.0/applications/dependency-injection/) 为应用的其余部分提供配置的容器实例,例如:

export function initialize(application) {
  var container = CloudKit.configure(config).getDefaultContainer();
  application.register('ckcontainer:main', container);
  application.inject('route', 'ckcontainer', 'ckcontainer:main');
}
export default {
  name: 'ckcontainer',
  initialize: initialize
};

然后在路由中,您可以获得如下所示的引用:

export default Ember.Route.extend({
  activate() {
    // The ckcontainer property is injected into all routes
    var db = this.get('ckcontainer').privateCloudDatabase;
  }
});

-HTH