Esempio n. 1
0
  setupContext() {
    var subjectName = this.subjectName;
    var container = this.container;

    var factory = function() {
      return container.factoryFor
        ? container.factoryFor(subjectName)
        : container.lookupFactory(subjectName);
    };

    super.setupContext({
      container: this.container,
      registry: this.registry,
      factory: factory,
      register() {
        var target = this.registry || this.container;
        return target.register.apply(target, arguments);
      },
    });

    if (setOwner) {
      setOwner(this.context, this.container.owner);
    }

    this.setupInject();
  }
Esempio n. 2
0
  getRecord(properties) {
    if (!this._record && !this._isDematerializing) {
      heimdall.increment(materializeRecord);
      let token = heimdall.start('InternalModel.getRecord');

      // lookupFactory should really return an object that creates
      // instances with the injections applied
      let createOptions = {
        store: this.store,
        _internalModel: this,
        id: this.id,
        currentState: this.currentState,
        isError: this.isError,
        adapterError: this.error
      };

      if (typeof properties === 'object' && properties !== null) {
        emberAssign(createOptions, properties);
      }

      if (setOwner) {
        // ensure that `getOwner(this)` works inside a model instance
        setOwner(createOptions, getOwner(this.store));
      } else {
        createOptions.container = this.store.container;
      }

      this._record = this.store.modelFactoryFor(this.modelName).create(createOptions);

      this._triggerDeferredTriggers();
      heimdall.stop(token);
    }

    return this._record;
  }
test( "Non existing record", async assert => {

	assert.expect( 9 );

	owner.register( "adapter:settings", Adapter.extend({
		async findAll() {
			assert.ok( true, "Calls findAll()" );
			return [];
		},
		async createRecord() {
			assert.ok( true, "Calls createRecord()" );
		},
		async updateRecord() {
			assert.ok( true, "Calls updateRecord()" );
		}
	}) );

	assert.ok( SettingsService.isServiceFactory, "Is a service factory object" );

	const settingsService = SettingsService.extend({
		init() {
			setOwner( this, owner );
			this._super( ...arguments );
		}
	}).create();

	assert.strictEqual(
		get( settingsService, "content" ),
		null,
		"Doesn't have content initially"
	);
	assert.strictEqual(
		get( settingsService, "foo" ),
		undefined,
		"Foo property does not exist yet"
	);

	await new Promise( resolve => {
		settingsService.on( "initialized", resolve );
	});

	assert.ok( env.store.hasRecordForId( "settings", 1 ), "Settings record with ID 1 exists" );

	assert.strictEqual(
		get( settingsService, "foo" ),
		"bar",
		"Properties are proxied once initialized"
	);

	await new Promise( resolve => {
		settingsService.on( "didUpdate", () => {
			assert.ok( true, "Supports the didUpdate event" );
			resolve();
		});
		set( settingsService, "foo", "baz" );
		get( settingsService, "content" ).save();
	});

});
test( "Existing record", async assert => {

	assert.expect( 5 );

	owner.register( "adapter:settings", Adapter.extend({
		async findAll() {
			assert.ok( true, "Calls findAll()" );
			return [{
				id: 1
			}];
		}
	}) );

	const settingsService = SettingsService.extend({
		init() {
			setOwner( this, owner );
			this._super( ...arguments );
		}
	}).create();

	assert.strictEqual(
		get( settingsService, "content" ),
		null,
		"Doesn't have content initially"
	);
	assert.strictEqual(
		get( settingsService, "foo" ),
		undefined,
		"Foo property does not exist yet"
	);

	await new Promise( resolve => {
		settingsService.on( "initialized", resolve );
	});

	assert.ok( env.store.hasRecordForId( "settings", 1 ), "Settings record with ID 1 exists" );

	assert.strictEqual(
		get( settingsService, "foo" ),
		"bar",
		"Properties are proxied once initialized"
	);

});
    beforeEach(function() {
      session = {
        restore() {}
      };

      ApplicationRoute = Route.extend({
        beforeModel() {
          return RSVP.resolve('test');
        }
      });

      resolveStub.withArgs('route:application').returns(ApplicationRoute);
      setupSessionRestoration(registry);

      route = ApplicationRoute.create({ container: {} });

      if (setOwner) {
        setOwner(route, { lookup() {} });
      }

      const owner = getOwner(route);
      sinon.stub(owner, 'lookup').withArgs('session:main').returns(session);
    });
Esempio n. 6
0
  getRecord(properties) {
    if (!this._record && !this._isDematerializing) {
      heimdall.increment(materializeRecord);
      let token = heimdall.start('InternalModel.getRecord');

      // lookupFactory should really return an object that creates
      // instances with the injections applied
      let createOptions = {
        store: this.store,
        _internalModel: this,
        currentState: this.currentState,
        isError: this.isError,
        adapterError: this.error
      };

      if (properties !== undefined) {
        assert(`You passed '${properties}' as properties for record creation instead of an object.`, typeof properties === 'object' && properties !== null);
        let classFields = this.getFields();
        let relationships = this._relationships;
        let propertyNames = Object.keys(properties);

        for (let i = 0; i < propertyNames.length; i++) {
          let name = propertyNames[i];
          let fieldType = classFields.get(name);
          let propertyValue = properties[name];

          if (name === 'id') {
            this.setId(propertyValue);
            continue;
          }

          switch (fieldType) {
            case 'attribute':
              this.setDirtyAttribute(name, propertyValue);
              break;
            case 'belongsTo':
              this.setDirtyBelongsTo(name, propertyValue);
              relationships.get(name).setHasAnyRelationshipData(true);
              relationships.get(name).setRelationshipIsEmpty(false);
              break;
            case 'hasMany':
              this.setDirtyHasMany(name, propertyValue);
              relationships.get(name).setHasAnyRelationshipData(true);
              relationships.get(name).setRelationshipIsEmpty(false);
              break;
            default:
              createOptions[name] = propertyValue;
          }
        }
      }

      if (setOwner) {
        // ensure that `getOwner(this)` works inside a model instance
        setOwner(createOptions, getOwner(this.store));
      } else {
        createOptions.container = this.store.container;
      }

      this._record = this.store.modelFactoryFor(this.modelName).create(createOptions);

      this._triggerDeferredTriggers();
      heimdall.stop(token);
    }

    return this._record;
  }
Esempio n. 7
0
  getRecord(properties) {
    if (!this._record && !this._isDematerializing) {
      heimdall.increment(materializeRecord);
      let token = heimdall.start('InternalModel.getRecord');
      let { store } = this;

      // lookupFactory should really return an object that creates
      // instances with the injections applied
      let createOptions = {
        store,
        _internalModel: this,
        currentState: this.currentState,
        isError: this.isError,
        adapterError: this.error,
      };

      if (properties !== undefined) {
        assert(
          `You passed '${properties}' as properties for record creation instead of an object.`,
          typeof properties === 'object' && properties !== null
        );

        if ('id' in properties) {
          this.setId(properties.id);
        }

        // convert relationship Records to ModelDatas before passing to ModelData
        let defs = store._relationshipsDefinitionFor(this.modelName);

        if (defs !== null) {
          let keys = Object.keys(properties);
          let relationshipValue;

          for (let i = 0; i < keys.length; i++) {
            let prop = keys[i];
            let def = defs[prop];

            if (def !== undefined) {
              if (def.kind === 'hasMany') {
                if (DEBUG) {
                  assertRecordsPassedToHasMany(properties[prop]);
                }
                relationshipValue = extractRecordDatasFromRecords(properties[prop]);
              } else {
                relationshipValue = extractRecordDataFromRecord(properties[prop]);
              }

              properties[prop] = relationshipValue;
            }
          }
        }
      }

      let additionalCreateOptions = this._modelData._initRecordCreateOptions(properties);
      Object.assign(createOptions, additionalCreateOptions);

      if (setOwner) {
        // ensure that `getOwner(this)` works inside a model instance
        setOwner(createOptions, getOwner(store));
      } else {
        createOptions.container = store.container;
      }

      this._record = store._modelFactoryFor(this.modelName).create(createOptions);

      this._triggerDeferredTriggers();
      heimdall.stop(token);
    }

    return this._record;
  }