@firestore-repository/firebase-js-sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +92 -0
- package/build/esm/index.d.ts +40 -0
- package/build/esm/index.js +212 -0
- package/package.json +53 -0
package/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Naoto Ikeno
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
@@ -0,0 +1,92 @@
|
|
1
|
+
[](https://badge.fury.io/js/firestore-repository)
|
2
|
+
[](https://github.com/ikenox/firestore-repository/actions/workflows/check-and-test.yaml)
|
3
|
+
[](https://opensource.org/licenses/MIT)
|
4
|
+
|
5
|
+
# firestore-repository
|
6
|
+
|
7
|
+
A minimum and universal Firestore ORM (Repository Pattern) for TypeScript
|
8
|
+
|
9
|
+
## Features
|
10
|
+
|
11
|
+
- 🚀 **Minimum**: Only a few straightforward interfaces and classes. You can easily start to use it immediately without learning a lot of things.
|
12
|
+
- 🌐 **Unopinionated**: This library does not introduce any additional concepts, and respects an interface of the official Firestore client library.
|
13
|
+
- ✅ **Type-safe**: This library provides the type-safe interface. It also covers the untyped parts of the official Firestore library.
|
14
|
+
- 🗄️ **Repository Pattern**: A simple and consistent way to access Firestore data.
|
15
|
+
|
16
|
+
## Installation
|
17
|
+
|
18
|
+
### For backend (with `@google-cloud/firestore` or `firebase-admin`)
|
19
|
+
|
20
|
+
```shell
|
21
|
+
npm install firestore-repository @firestore-repository/google-cloud-firestore
|
22
|
+
````
|
23
|
+
|
24
|
+
### For web frontend (with `firebase-js-sdk`)
|
25
|
+
|
26
|
+
```shell
|
27
|
+
npm install firestore-repository @firestore-repository/firebase-js-sdk
|
28
|
+
```
|
29
|
+
|
30
|
+
## Basic usage
|
31
|
+
|
32
|
+
```ts
|
33
|
+
import { id, implicit, rootCollection } from 'firestore-repository/schema';
|
34
|
+
import { condition as $, limit, query, where } from 'firestore-repository/query';
|
35
|
+
|
36
|
+
// For backend
|
37
|
+
import { Firestore } from '@google-cloud/firestore';
|
38
|
+
import { Repository } from '@firestore-repository/google-cloud-firestore';
|
39
|
+
const db = new Firestore();
|
40
|
+
const repository = new Repository(authors, db);
|
41
|
+
|
42
|
+
// For web frontend
|
43
|
+
import { getFirestore } from '@firebase/firestore';
|
44
|
+
import { Repository } from '@firestore-repository/firebase-js-sdk';
|
45
|
+
const db = getFirestore();
|
46
|
+
const repository = new Repository(authors, db);
|
47
|
+
|
48
|
+
// define a collection
|
49
|
+
const authors = rootCollection({
|
50
|
+
name: 'Authors',
|
51
|
+
id: id('authorId'),
|
52
|
+
data: implicit(
|
53
|
+
(data: {
|
54
|
+
name: string;
|
55
|
+
profile: {
|
56
|
+
age: number;
|
57
|
+
gender?: 'male' | 'female';
|
58
|
+
};
|
59
|
+
tag: string[];
|
60
|
+
registeredAt: Timestamp;
|
61
|
+
}) => ({
|
62
|
+
...data,
|
63
|
+
registeredAt: data.registeredAt.toDate(),
|
64
|
+
}),
|
65
|
+
),
|
66
|
+
});
|
67
|
+
|
68
|
+
// set
|
69
|
+
await repository.set({
|
70
|
+
authorId: 'author1',
|
71
|
+
name: 'John Doe',
|
72
|
+
profile: {
|
73
|
+
age: 42,
|
74
|
+
gender: 'male',
|
75
|
+
},
|
76
|
+
tag: ['new'],
|
77
|
+
registeredAt: new Date(),
|
78
|
+
});
|
79
|
+
|
80
|
+
// get
|
81
|
+
const doc = await repository.get({ authorId: 'author1' });
|
82
|
+
console.info(doc);
|
83
|
+
|
84
|
+
// query snapshot
|
85
|
+
const q1 = query(authors, where($('profile.age', '>=', 20)), limit(10));
|
86
|
+
const docs = await repository.list(q1);
|
87
|
+
console.log(docs);
|
88
|
+
|
89
|
+
// listen query
|
90
|
+
const q2 = query(authors, where($('tag', 'array-contains', 'new')), limit(10));
|
91
|
+
repository.listOnSnapshot(q2, (docs) => { console.log(docs); });
|
92
|
+
```
|
@@ -0,0 +1,40 @@
|
|
1
|
+
import { type DocumentReference, type DocumentSnapshot, type Firestore, type Query as FirestoreQuery, Transaction, type WriteBatch } from '@firebase/firestore';
|
2
|
+
import type { AggregateQuery, Aggregated } from 'firestore-repository/aggregate';
|
3
|
+
import type { WriteDocumentData } from 'firestore-repository/document';
|
4
|
+
import type { Query } from 'firestore-repository/query';
|
5
|
+
import type * as repository from 'firestore-repository/repository';
|
6
|
+
import { type CollectionSchema, type DocPathElement, type Id, type Model, type ParentId } from 'firestore-repository/schema';
|
7
|
+
export type Env = {
|
8
|
+
transaction: Transaction;
|
9
|
+
writeBatch: WriteBatch;
|
10
|
+
query: FirestoreQuery;
|
11
|
+
};
|
12
|
+
export type TransactionOption = repository.TransactionOption<Env>;
|
13
|
+
export type WriteTransactionOption = repository.WriteTransactionOption<Env>;
|
14
|
+
export declare class Repository<T extends CollectionSchema = CollectionSchema> implements repository.Repository<T, Env> {
|
15
|
+
readonly collection: T;
|
16
|
+
readonly db: Firestore;
|
17
|
+
constructor(collection: T, db: Firestore);
|
18
|
+
get(id: Id<T>, options?: TransactionOption): Promise<Model<T> | undefined>;
|
19
|
+
getOnSnapshot(id: Id<T>, next: (snapshot: Model<T> | undefined) => void, error?: (error: Error) => void, complete?: () => void): repository.Unsubscribe;
|
20
|
+
list(query: Query<T>): Promise<Model<T>[]>;
|
21
|
+
listOnSnapshot(query: Query<T>, next: (snapshot: Model<T>[]) => void, error?: (error: Error) => void, complete?: () => void): repository.Unsubscribe;
|
22
|
+
aggregate<U extends AggregateQuery<T>>(aggregate: U): Promise<Aggregated<U>>;
|
23
|
+
set(doc: Model<T>, options?: WriteTransactionOption): Promise<void>;
|
24
|
+
delete(id: Id<T>, options?: WriteTransactionOption): Promise<void>;
|
25
|
+
batchSet(docs: Model<T>[], options?: WriteTransactionOption): Promise<void>;
|
26
|
+
batchDelete(ids: Id<T>[], options?: WriteTransactionOption): Promise<void>;
|
27
|
+
protected batchWriteOperation<U>(targets: U[], runner: {
|
28
|
+
batch: (batch: WriteBatch, target: U) => void;
|
29
|
+
transaction: (transaction: Transaction, target: U) => void;
|
30
|
+
}, options?: WriteTransactionOption): Promise<void>;
|
31
|
+
protected docRef(id: Id<T>): DocumentReference<import("@firebase/firestore").DocumentData, import("@firebase/firestore").DocumentData>;
|
32
|
+
protected collectionRef(parentId: ParentId<T>): import("@firebase/firestore").CollectionReference<import("@firebase/firestore").DocumentData, import("@firebase/firestore").DocumentData>;
|
33
|
+
protected fromFirestore(doc: DocumentSnapshot): Model<T> | undefined;
|
34
|
+
protected toFirestoreData(data: Model<T>): WriteDocumentData;
|
35
|
+
}
|
36
|
+
/**
|
37
|
+
* Obtain document path elements from DocumentReference
|
38
|
+
*/
|
39
|
+
export declare const docPathElements: (doc: DocumentReference) => [DocPathElement, ...DocPathElement[]];
|
40
|
+
export declare const toFirestoreQuery: (db: Firestore, query: Query) => FirestoreQuery;
|
@@ -0,0 +1,212 @@
|
|
1
|
+
import { QueryCompositeFilterConstraint, Transaction, and, average, collection, collectionGroup, count, deleteDoc, doc, endAt, endBefore, query as firestoreQuery, getAggregateFromServer, getDoc, getDocs, limit, limitToLast, onSnapshot, or, orderBy, setDoc, startAfter, startAt, sum, where, writeBatch, } from '@firebase/firestore';
|
2
|
+
import { collectionPath, docPath, } from 'firestore-repository/schema';
|
3
|
+
import { assertNever } from 'firestore-repository/util';
|
4
|
+
export class Repository {
|
5
|
+
collection;
|
6
|
+
db;
|
7
|
+
constructor(collection, db) {
|
8
|
+
this.collection = collection;
|
9
|
+
this.db = db;
|
10
|
+
}
|
11
|
+
async get(id, options) {
|
12
|
+
const doc = await (options?.tx ? options.tx.get(this.docRef(id)) : getDoc(this.docRef(id)));
|
13
|
+
return this.fromFirestore(doc);
|
14
|
+
}
|
15
|
+
getOnSnapshot(id, next, error, complete) {
|
16
|
+
return onSnapshot(this.docRef(id), {
|
17
|
+
next: (doc) => {
|
18
|
+
next(this.fromFirestore(doc));
|
19
|
+
},
|
20
|
+
error: (e) => error?.(e),
|
21
|
+
complete: () => {
|
22
|
+
complete?.();
|
23
|
+
},
|
24
|
+
});
|
25
|
+
}
|
26
|
+
async list(query) {
|
27
|
+
const { docs } = await getDocs(toFirestoreQuery(this.db, query));
|
28
|
+
return docs.map((doc) =>
|
29
|
+
// biome-ignore lint/style/noNonNullAssertion: query result item should not be null
|
30
|
+
this.fromFirestore(doc));
|
31
|
+
}
|
32
|
+
listOnSnapshot(query, next, error, complete) {
|
33
|
+
return onSnapshot(toFirestoreQuery(this.db, query), {
|
34
|
+
next: ({ docs }) => {
|
35
|
+
// biome-ignore lint/style/noNonNullAssertion: query result item should not be null
|
36
|
+
next(docs.map((doc) => this.fromFirestore(doc)));
|
37
|
+
},
|
38
|
+
error: (e) => error?.(e),
|
39
|
+
complete: () => {
|
40
|
+
complete?.();
|
41
|
+
},
|
42
|
+
});
|
43
|
+
}
|
44
|
+
async aggregate(aggregate) {
|
45
|
+
const aggregateSpec = {};
|
46
|
+
for (const [k, v] of Object.entries(aggregate.spec)) {
|
47
|
+
switch (v.kind) {
|
48
|
+
case 'count':
|
49
|
+
aggregateSpec[k] = count();
|
50
|
+
break;
|
51
|
+
case 'sum':
|
52
|
+
aggregateSpec[k] = sum(v.path);
|
53
|
+
break;
|
54
|
+
case 'average':
|
55
|
+
aggregateSpec[k] = average(v.path);
|
56
|
+
break;
|
57
|
+
default:
|
58
|
+
return assertNever(v);
|
59
|
+
}
|
60
|
+
}
|
61
|
+
const res = await getAggregateFromServer(toFirestoreQuery(this.db, aggregate.query), aggregateSpec);
|
62
|
+
return res.data();
|
63
|
+
}
|
64
|
+
async set(doc, options) {
|
65
|
+
const data = this.toFirestoreData(doc);
|
66
|
+
await (options?.tx
|
67
|
+
? options.tx instanceof Transaction
|
68
|
+
? options.tx.set(this.docRef(doc), data)
|
69
|
+
: options.tx.set(this.docRef(doc), data)
|
70
|
+
: setDoc(this.docRef(doc), data));
|
71
|
+
}
|
72
|
+
async delete(id, options) {
|
73
|
+
await (options?.tx ? options.tx.delete(this.docRef(id)) : deleteDoc(this.docRef(id)));
|
74
|
+
}
|
75
|
+
async batchSet(docs, options) {
|
76
|
+
await this.batchWriteOperation(docs, {
|
77
|
+
batch: (batch, doc) => batch.set(this.docRef(doc), this.toFirestoreData(doc)),
|
78
|
+
transaction: (tx, doc) => tx.set(this.docRef(doc), this.toFirestoreData(doc)),
|
79
|
+
}, options);
|
80
|
+
}
|
81
|
+
async batchDelete(ids, options) {
|
82
|
+
await this.batchWriteOperation(ids, {
|
83
|
+
batch: (batch, id) => batch.delete(this.docRef(id)),
|
84
|
+
transaction: (tx, id) => tx.delete(this.docRef(id)),
|
85
|
+
}, options);
|
86
|
+
}
|
87
|
+
async batchWriteOperation(targets, runner, options) {
|
88
|
+
const tx = options?.tx;
|
89
|
+
if (tx) {
|
90
|
+
if (tx instanceof Transaction) {
|
91
|
+
targets.forEach((target) => runner.transaction(tx, target));
|
92
|
+
}
|
93
|
+
else {
|
94
|
+
targets.forEach((target) => runner.batch(tx, target));
|
95
|
+
}
|
96
|
+
}
|
97
|
+
else {
|
98
|
+
const batch = writeBatch(this.db);
|
99
|
+
targets.forEach((target) => runner.batch(batch, target));
|
100
|
+
await batch.commit();
|
101
|
+
}
|
102
|
+
}
|
103
|
+
docRef(id) {
|
104
|
+
return doc(this.db, docPath(this.collection, id));
|
105
|
+
}
|
106
|
+
collectionRef(parentId) {
|
107
|
+
return collection(this.db, collectionPath(this.collection, parentId));
|
108
|
+
}
|
109
|
+
fromFirestore(doc) {
|
110
|
+
const data = doc.data();
|
111
|
+
const [id, ...parentPath] = docPathElements(doc.ref);
|
112
|
+
return data
|
113
|
+
? {
|
114
|
+
...this.collection.data.from(data),
|
115
|
+
...this.collection.collectionPath.from(parentPath),
|
116
|
+
...this.collection.id.from(id.id),
|
117
|
+
}
|
118
|
+
: undefined;
|
119
|
+
}
|
120
|
+
toFirestoreData(data) {
|
121
|
+
return this.collection.data.to(data);
|
122
|
+
}
|
123
|
+
}
|
124
|
+
/**
|
125
|
+
* Obtain document path elements from DocumentReference
|
126
|
+
*/
|
127
|
+
export const docPathElements = (doc) => {
|
128
|
+
const parentPath = [];
|
129
|
+
let cursor = doc.parent.parent;
|
130
|
+
while (cursor) {
|
131
|
+
parentPath.push({ id: cursor.id, collection: cursor.parent.id });
|
132
|
+
cursor = cursor.parent.parent;
|
133
|
+
}
|
134
|
+
return [{ collection: doc.parent.id, id: doc.id }, ...parentPath];
|
135
|
+
};
|
136
|
+
export const toFirestoreQuery = (db, query) => {
|
137
|
+
const { filter, nonFilter } = (query.constraints ?? []).reduce((acc, constraint) => {
|
138
|
+
switch (constraint.kind) {
|
139
|
+
case 'where': {
|
140
|
+
const filter = toFirestoreQueryFilterConstraint(constraint.filter);
|
141
|
+
acc.filter = acc.filter ? and(acc.filter, filter) : filter;
|
142
|
+
break;
|
143
|
+
}
|
144
|
+
case 'orderBy':
|
145
|
+
acc.nonFilter.push(orderBy(constraint.field, constraint.direction));
|
146
|
+
break;
|
147
|
+
case 'limit':
|
148
|
+
acc.nonFilter.push(limit(constraint.limit));
|
149
|
+
break;
|
150
|
+
case 'limitToLast':
|
151
|
+
acc.nonFilter.push(limitToLast(constraint.limit));
|
152
|
+
break;
|
153
|
+
case 'offset':
|
154
|
+
// https://github.com/firebase/firebase-js-sdk/issues/479
|
155
|
+
throw new Error('firestore-js-sdk does not support offset constraint');
|
156
|
+
case 'startAt': {
|
157
|
+
const { cursor } = constraint;
|
158
|
+
acc.nonFilter.push(startAt(...cursor));
|
159
|
+
break;
|
160
|
+
}
|
161
|
+
case 'startAfter': {
|
162
|
+
const { cursor } = constraint;
|
163
|
+
acc.nonFilter.push(startAfter(...cursor));
|
164
|
+
break;
|
165
|
+
}
|
166
|
+
case 'endAt': {
|
167
|
+
const { cursor } = constraint;
|
168
|
+
acc.nonFilter.push(endAt(...cursor));
|
169
|
+
break;
|
170
|
+
}
|
171
|
+
case 'endBefore': {
|
172
|
+
const { cursor } = constraint;
|
173
|
+
acc.nonFilter.push(endBefore(...cursor));
|
174
|
+
break;
|
175
|
+
}
|
176
|
+
default:
|
177
|
+
return assertNever(constraint);
|
178
|
+
}
|
179
|
+
return acc;
|
180
|
+
}, { nonFilter: [] });
|
181
|
+
let base;
|
182
|
+
switch (query.base.kind) {
|
183
|
+
case 'collection':
|
184
|
+
base = collection(db, collectionPath(query.base.collection, query.base.parentId));
|
185
|
+
break;
|
186
|
+
case 'collectionGroup':
|
187
|
+
base = collectionGroup(db, query.base.collection.name);
|
188
|
+
break;
|
189
|
+
case 'extends':
|
190
|
+
base = toFirestoreQuery(db, query.base.query);
|
191
|
+
break;
|
192
|
+
default:
|
193
|
+
base = assertNever(query.base);
|
194
|
+
}
|
195
|
+
return filter
|
196
|
+
? filter instanceof QueryCompositeFilterConstraint
|
197
|
+
? firestoreQuery(base, filter, ...nonFilter)
|
198
|
+
: firestoreQuery(base, filter, ...nonFilter)
|
199
|
+
: firestoreQuery(base, ...nonFilter);
|
200
|
+
};
|
201
|
+
const toFirestoreQueryFilterConstraint = (expr) => {
|
202
|
+
switch (expr.kind) {
|
203
|
+
case 'where':
|
204
|
+
return where(expr.fieldPath, expr.opStr, expr.value);
|
205
|
+
case 'or':
|
206
|
+
return or(...expr.filters.map(toFirestoreQueryFilterConstraint));
|
207
|
+
case 'and':
|
208
|
+
return and(...expr.filters.map(toFirestoreQueryFilterConstraint));
|
209
|
+
default:
|
210
|
+
return assertNever(expr);
|
211
|
+
}
|
212
|
+
};
|
package/package.json
ADDED
@@ -0,0 +1,53 @@
|
|
1
|
+
{
|
2
|
+
"name": "@firestore-repository/firebase-js-sdk",
|
3
|
+
"version": "0.1.0",
|
4
|
+
"description": "A minimum and universal Firestore ORM (Repository Pattern) for TypeScript",
|
5
|
+
"homepage": "https://github.com/ikenox/firestore-repository",
|
6
|
+
"repository": {
|
7
|
+
"type": "git",
|
8
|
+
"url": "https://github.com/ikenox/firestore-repository.git"
|
9
|
+
},
|
10
|
+
"type": "module",
|
11
|
+
"dependencies": {
|
12
|
+
"@firebase/firestore": "^4.7.5",
|
13
|
+
"firestore-repository": "0.1.0"
|
14
|
+
},
|
15
|
+
"devDependencies": {
|
16
|
+
"@firebase/app": "^0.10.16"
|
17
|
+
},
|
18
|
+
"exports": {
|
19
|
+
".": {
|
20
|
+
"import": {
|
21
|
+
"types": "./build/esm/index.d.ts",
|
22
|
+
"default": "./build/esm/index.js"
|
23
|
+
}
|
24
|
+
},
|
25
|
+
"./*": {
|
26
|
+
"import": {
|
27
|
+
"types": "./build/esm/*.d.ts",
|
28
|
+
"default": "./build/esm/*.js"
|
29
|
+
}
|
30
|
+
}
|
31
|
+
},
|
32
|
+
"files": [
|
33
|
+
"build",
|
34
|
+
"!**/*.tsbuildinfo"
|
35
|
+
],
|
36
|
+
"keywords": [
|
37
|
+
"firestore",
|
38
|
+
"orm",
|
39
|
+
"database",
|
40
|
+
"repository",
|
41
|
+
"firebase",
|
42
|
+
"firebase-js-sdk"
|
43
|
+
],
|
44
|
+
"author": "Naoto Ikeno <ikenox@gmail.com>",
|
45
|
+
"license": "MIT",
|
46
|
+
"publishConfig": {
|
47
|
+
"access": "public"
|
48
|
+
},
|
49
|
+
"scripts": {
|
50
|
+
"typecheck": "tsc --noEmit",
|
51
|
+
"build": "rm -rf build/ && tsc -b tsconfig.build.json"
|
52
|
+
}
|
53
|
+
}
|