Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support buildReference for one-to-many relationships #157

Merged
merged 2 commits into from
Jan 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions addon/adapters/cloud-firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,17 +331,20 @@ export default class CloudFirestoreAdapter extends Adapter {
relationship: HasManyRelationshipMeta,
): firebase.firestore.CollectionReference | firebase.firestore.Query {
const db = this.firebase.firestore();

if (relationship.options.buildReference) {
const collectionRef = relationship.options.buildReference(db, snapshot.record);

return relationship.options.filter?.(collectionRef, snapshot.record) || collectionRef;
}

const cardinality = snapshot.type.determineRelationshipType(relationship, store);

if (cardinality === 'manyToOne') {
const inverse = snapshot.type.inverseFor(relationship.key, store);
const collectionName = buildCollectionName(snapshot.modelName.toString());
const parentDocRef = db.doc(`${collectionName}/${snapshot.id}`);
const collectionRef = db.collection(url).where(inverse.name, '==', parentDocRef);

return relationship.options.filter?.(collectionRef, snapshot.record) || collectionRef;
} if (relationship.options.buildReference) {
const collectionRef = relationship.options.buildReference(db, snapshot.record);
const snapshotCollectionName = buildCollectionName(snapshot.modelName.toString());
const snapshotDocRef = db.doc(`${snapshotCollectionName}/${snapshot.id}`);
const collectionRef = db.collection(url).where(inverse.name, '==', snapshotDocRef);

return relationship.options.filter?.(collectionRef, snapshot.record) || collectionRef;
}
Expand Down
24 changes: 19 additions & 5 deletions addon/serializers/cloud-firestore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ interface ResourceHash {
[key: string]: string | Links | firebase.firestore.CollectionReference;
}

interface RelationshipDefinition {
key: string;
type: string;
options: {
buildReference?(db: firebase.firestore.Firestore): firebase.firestore.CollectionReference
};
}

interface ModelClass {
modelName: string;
determineRelationshipType(descriptor: { kind: string, type: string }, store: Store): string;
Expand Down Expand Up @@ -89,16 +97,22 @@ export default class CloudFirestoreSerializer extends JSONSerializer {
public serializeBelongsTo(
snapshot: DS.Snapshot,
json: { [key: string]: string | null | firebase.firestore.DocumentReference },
relationship: { key: string, type: string },
relationship: RelationshipDefinition,
): void {
super.serializeBelongsTo(snapshot, json, relationship);

if (json[relationship.key]) {
const collectionName = buildCollectionName(relationship.type);
const docId = json[relationship.key];
const path = `${collectionName}/${docId}`;
const db = this.firebase.firestore();
const docId = json[relationship.key] as string;

json[relationship.key] = this.firebase.firestore().doc(path);
if (relationship.options.buildReference) {
json[relationship.key] = relationship.options.buildReference(db).doc(docId);
} else {
const collectionName = buildCollectionName(relationship.type);
const path = `${collectionName}/${docId}`;

json[relationship.key] = db.doc(path);
}
}
}

Expand Down
14 changes: 12 additions & 2 deletions docs/relationships.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ Indicates if the record will update in realtime

**Type:** `boolean`

### `buildReference`

Hook for providing a custom collection reference.

**Type:** `function`

**Params:**

| Name | Type | Description |
| -------| ------------------------------------------------------------------------------------------------------------ | ----------------- |
| db | [`firebase.firestore.Firestore`](https://firebase.google.com/docs/reference/js/firebase.firestore.Firestore) | |

## `hasMany`

The optional configs are available by passing it as a param.
Expand Down Expand Up @@ -54,8 +66,6 @@ Indicates if the record will update in realtime after creating it

Hook for providing a custom collection reference.

This is ignored when the relationship is a many-to-one type.

**Type:** `function`

**Params:**
Expand Down
20 changes: 20 additions & 0 deletions tests/acceptance/features-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,26 @@ module('Acceptance | features', function (hooks) {
assert.dom('[data-test-age="user_a"]').hasNoText();
});

test('should be able to create record with belongs to build reference', async function (assert) {
assert.expect(4);

// Arrange
await visit('/features');

// Act
await click('[data-test-button="create-record-with-belongs-to-build-reference"]');

// Assert
await waitFor('[data-test-id]', { timeout: 5000 });
assert.dom('[data-test-id="user_a"]').hasText('user_a');
assert.dom('[data-test-name="user_a"]').hasText('user_a');
assert.dom('[data-test-age="user_a"]').hasNoText();

const createdRecord = await db.doc('posts/new_post').get();

assert.equal(createdRecord.get('publisher').path, 'publishers/user_a');
});

test('should update record', async function (assert) {
assert.expect(1);

Expand Down
13 changes: 13 additions & 0 deletions tests/dummy/app/controllers/features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ export default class FeaturesController extends Controller {
this.users = [author];
}

@action
public async handleCreateRecordWithBelongsToBuildReference(): Promise<void> {
const user = await this.store.findRecord('user', 'user_a');
const post = await this.store.createRecord('post', {
id: 'new_post',
publisher: user,
title: 'What does having it all mean to you? (By: Gabe Lewis)',
}).save();
const publisher = await post.get('publisher');

this.users = [publisher];
}

@action
public async handleUpdateRecordClick(): Promise<void> {
const user = await this.store.findRecord('user', 'user_a');
Expand Down
12 changes: 12 additions & 0 deletions tests/dummy/app/models/post.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
/* eslint @typescript-eslint/ban-ts-comment: off */

import Model, { attr, belongsTo } from '@ember-data/model';

import firebase from 'firebase/app';

export default class PostModel extends Model.extend({
title: attr('string'),
createdOn: attr('timestamp'),
author: belongsTo('user'),
group: belongsTo('group'),
publisher: belongsTo('user', {
inverse: null,

// @ts-ignore: TODO - find a way to set custom property in RelationshipOptions interface
buildReference(db: firebase.firestore.Firestore) {
return db.collection('publishers');
},
}),
}) {}

// DO NOT DELETE: this is how TypeScript knows how to look up your models.
Expand Down
4 changes: 4 additions & 0 deletions tests/dummy/app/templates/features.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@
Create record without belongs to relationship
</button>

<button type="button" data-test-button="create-record-with-belongs-to-build-reference" {{on 'click' this.handleCreateRecordWithBelongsToBuildReference}}>
Create record with belongs to build reference
</button>

<button type="button" data-test-button="update-record" {{on 'click' this.handleUpdateRecordClick}}>
Update record
</button>
Expand Down
5 changes: 1 addition & 4 deletions tests/unit/adapters/cloud-firestore-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,13 +444,11 @@ module('Unit | Adapter | cloud firestore', function (hooks) {
assert.ok(inverseForStub.calledWithExactly(relationship.key, store));
});

test('should be able to fetch with a custom reference when not a many-to-one cardinality', async function (assert) {
test('should be able to fetch with a custom reference', async function (assert) {
// Arrange
const store = { normalize: sinon.stub(), push: sinon.stub() };
const determineRelationshipTypeStub = sinon.stub().returns('manyToNone');
const snapshot = {
record: EmberObject.create({ id: 'user_a' }),
type: { determineRelationshipType: determineRelationshipTypeStub },
};
const url = null;
const relationship = {
Expand All @@ -474,7 +472,6 @@ module('Unit | Adapter | cloud firestore', function (hooks) {
// Assert
assert.equal(result[0].id, 'post_b');
assert.equal(result[0].title, 'post_b');
assert.ok(determineRelationshipTypeStub.calledWithExactly(relationship, store));
});
});

Expand Down