@firestore-repository/google-cloud-firestore 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 +59 -0
- package/build/esm/index.js +215 -0
- package/package.json +51 -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,59 @@
|
|
1
|
+
import { type DocumentReference, type DocumentSnapshot, Filter, type Firestore, type Query as FirestoreQuery, Transaction, type WriteBatch } from '@google-cloud/firestore';
|
2
|
+
import type { AggregateQuery, Aggregated } from 'firestore-repository/aggregate';
|
3
|
+
import type { WriteDocumentData } from 'firestore-repository/document';
|
4
|
+
import type { FilterExpression, Offset, Query } from 'firestore-repository/query';
|
5
|
+
import type * as repository from 'firestore-repository/repository';
|
6
|
+
import { type CollectionSchema, type DocPathElement, type Id, type Model } 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): repository.Unsubscribe;
|
20
|
+
list(query: Query<T>): Promise<Model<T>[]>;
|
21
|
+
listOnSnapshot(query: Query<T>, next: (snapshot: Model<T>[]) => void, error?: (error: Error) => void): repository.Unsubscribe;
|
22
|
+
aggregate<U extends AggregateQuery<T>>(aggregate: U): Promise<Aggregated<U>>;
|
23
|
+
/**
|
24
|
+
* Create a new document
|
25
|
+
* @throws If the document already exists
|
26
|
+
*/
|
27
|
+
create(doc: Model<T>, options?: WriteTransactionOption): Promise<void>;
|
28
|
+
set(doc: Model<T>, options?: WriteTransactionOption): Promise<void>;
|
29
|
+
delete(id: Id<T>, options?: WriteTransactionOption): Promise<void>;
|
30
|
+
/**
|
31
|
+
* Get documents by multiple ID
|
32
|
+
* example: [{id:1},{id:2},{id:5},{id:1}] -> [doc1,doc2,undefined,doc1]
|
33
|
+
*/
|
34
|
+
batchGet(ids: Id<T>[], options?: TransactionOption): Promise<(Model<T> | undefined)[]>;
|
35
|
+
batchSet(docs: Model<T>[], options?: WriteTransactionOption): Promise<void>;
|
36
|
+
/**
|
37
|
+
* Create multiple documents
|
38
|
+
* The entire operation will fail if one creation fails
|
39
|
+
*/
|
40
|
+
batchCreate(docs: Model<T>[], options?: WriteTransactionOption): Promise<void>;
|
41
|
+
batchDelete(ids: Id<T>[], options?: WriteTransactionOption): Promise<void>;
|
42
|
+
protected batchWriteOperation<U>(targets: U[], runner: {
|
43
|
+
batch: (batch: WriteBatch, target: U) => void;
|
44
|
+
transaction: (transaction: Transaction, target: U) => void;
|
45
|
+
}, options?: WriteTransactionOption): Promise<void>;
|
46
|
+
protected docRef(id: Id<T>): DocumentReference<FirebaseFirestore.DocumentData, FirebaseFirestore.DocumentData>;
|
47
|
+
protected fromFirestore(doc: DocumentSnapshot): Model<T> | undefined;
|
48
|
+
protected toFirestoreData(data: Model<T>): WriteDocumentData;
|
49
|
+
}
|
50
|
+
/**
|
51
|
+
* Obtain document path elements from DocumentReference
|
52
|
+
*/
|
53
|
+
export declare const docPathElements: (doc: DocumentReference) => [DocPathElement, ...DocPathElement[]];
|
54
|
+
export declare const toFirestoreQuery: (db: Firestore, query: Query) => FirestoreQuery;
|
55
|
+
export declare const toFirestoreFilter: (expr: FilterExpression) => Filter;
|
56
|
+
/**
|
57
|
+
* A query offset constraint
|
58
|
+
*/
|
59
|
+
export declare const offset: (offset: number) => Offset;
|
@@ -0,0 +1,215 @@
|
|
1
|
+
import { AggregateField, Filter, Transaction, } from '@google-cloud/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)) : this.docRef(id).get());
|
13
|
+
return this.fromFirestore(doc);
|
14
|
+
}
|
15
|
+
getOnSnapshot(id, next, error) {
|
16
|
+
return this.docRef(id).onSnapshot((snapshot) => {
|
17
|
+
next(this.fromFirestore(snapshot));
|
18
|
+
}, error);
|
19
|
+
}
|
20
|
+
async list(query) {
|
21
|
+
const { docs } = await toFirestoreQuery(this.db, query).get();
|
22
|
+
return docs.map((doc) =>
|
23
|
+
// biome-ignore lint/style/noNonNullAssertion: Query result items should have data
|
24
|
+
this.fromFirestore(doc));
|
25
|
+
}
|
26
|
+
listOnSnapshot(query, next, error) {
|
27
|
+
return toFirestoreQuery(this.db, query).onSnapshot((snapshot) => {
|
28
|
+
// biome-ignore lint/style/noNonNullAssertion: Query result items should have data
|
29
|
+
next(snapshot.docs.map((doc) => this.fromFirestore(doc)));
|
30
|
+
}, error);
|
31
|
+
}
|
32
|
+
async aggregate(aggregate) {
|
33
|
+
const aggregateSpec = {};
|
34
|
+
for (const [k, v] of Object.entries(aggregate.spec)) {
|
35
|
+
switch (v.kind) {
|
36
|
+
case 'count':
|
37
|
+
aggregateSpec[k] = AggregateField.count();
|
38
|
+
break;
|
39
|
+
case 'sum':
|
40
|
+
aggregateSpec[k] = AggregateField.sum(v.path);
|
41
|
+
break;
|
42
|
+
case 'average':
|
43
|
+
aggregateSpec[k] = AggregateField.average(v.path);
|
44
|
+
break;
|
45
|
+
default:
|
46
|
+
return assertNever(v);
|
47
|
+
}
|
48
|
+
}
|
49
|
+
const res = await toFirestoreQuery(this.db, aggregate.query).aggregate(aggregateSpec).get();
|
50
|
+
return res.data();
|
51
|
+
}
|
52
|
+
/**
|
53
|
+
* Create a new document
|
54
|
+
* @throws If the document already exists
|
55
|
+
*/
|
56
|
+
async create(doc, options) {
|
57
|
+
const data = this.toFirestoreData(doc);
|
58
|
+
await (options?.tx ? options.tx.create(this.docRef(doc), data) : this.docRef(doc).create(data));
|
59
|
+
}
|
60
|
+
async set(doc, options) {
|
61
|
+
const data = this.toFirestoreData(doc);
|
62
|
+
await (options?.tx
|
63
|
+
? options.tx instanceof Transaction
|
64
|
+
? options.tx.set(this.docRef(doc), data)
|
65
|
+
: options.tx.set(this.docRef(doc), data)
|
66
|
+
: this.docRef(doc).set(data));
|
67
|
+
}
|
68
|
+
async delete(id, options) {
|
69
|
+
await (options?.tx ? options.tx.delete(this.docRef(id)) : this.docRef(id).delete());
|
70
|
+
}
|
71
|
+
/**
|
72
|
+
* Get documents by multiple ID
|
73
|
+
* example: [{id:1},{id:2},{id:5},{id:1}] -> [doc1,doc2,undefined,doc1]
|
74
|
+
*/
|
75
|
+
async batchGet(ids, options) {
|
76
|
+
if (ids.length === 0) {
|
77
|
+
return [];
|
78
|
+
}
|
79
|
+
const docRefs = ids.map((id) => this.docRef(id));
|
80
|
+
const docs = await (options?.tx ? options.tx.getAll(...docRefs) : this.db.getAll(...docRefs));
|
81
|
+
return docs.map((doc) => this.fromFirestore(doc));
|
82
|
+
}
|
83
|
+
async batchSet(docs, options) {
|
84
|
+
await this.batchWriteOperation(docs, {
|
85
|
+
batch: (batch, doc) => batch.set(this.docRef(doc), this.toFirestoreData(doc)),
|
86
|
+
transaction: (tx, doc) => tx.set(this.docRef(doc), this.toFirestoreData(doc)),
|
87
|
+
}, options);
|
88
|
+
}
|
89
|
+
/**
|
90
|
+
* Create multiple documents
|
91
|
+
* The entire operation will fail if one creation fails
|
92
|
+
*/
|
93
|
+
async batchCreate(docs, options) {
|
94
|
+
await this.batchWriteOperation(docs, {
|
95
|
+
batch: (batch, doc) => batch.create(this.docRef(doc), this.toFirestoreData(doc)),
|
96
|
+
transaction: (tx, doc) => tx.create(this.docRef(doc), this.toFirestoreData(doc)),
|
97
|
+
}, options);
|
98
|
+
}
|
99
|
+
async batchDelete(ids, options) {
|
100
|
+
await this.batchWriteOperation(ids, {
|
101
|
+
batch: (batch, id) => batch.delete(this.docRef(id)),
|
102
|
+
transaction: (tx, id) => tx.delete(this.docRef(id)),
|
103
|
+
}, options);
|
104
|
+
}
|
105
|
+
async batchWriteOperation(targets, runner, options) {
|
106
|
+
const tx = options?.tx;
|
107
|
+
if (tx) {
|
108
|
+
if (tx instanceof Transaction) {
|
109
|
+
targets.forEach((target) => runner.transaction(tx, target));
|
110
|
+
}
|
111
|
+
else {
|
112
|
+
targets.forEach((target) => runner.batch(tx, target));
|
113
|
+
}
|
114
|
+
}
|
115
|
+
else {
|
116
|
+
const batch = this.db.batch();
|
117
|
+
targets.forEach((target) => runner.batch(batch, target));
|
118
|
+
await batch.commit();
|
119
|
+
}
|
120
|
+
}
|
121
|
+
docRef(id) {
|
122
|
+
return this.db.doc(docPath(this.collection, id));
|
123
|
+
}
|
124
|
+
fromFirestore(doc) {
|
125
|
+
const data = doc.data();
|
126
|
+
const [id, ...parentPath] = docPathElements(doc.ref);
|
127
|
+
return data
|
128
|
+
? {
|
129
|
+
...this.collection.data.from(data),
|
130
|
+
...this.collection.collectionPath.from(parentPath),
|
131
|
+
...this.collection.id.from(id.id),
|
132
|
+
}
|
133
|
+
: undefined;
|
134
|
+
}
|
135
|
+
toFirestoreData(data) {
|
136
|
+
return this.collection.data.to(data);
|
137
|
+
}
|
138
|
+
}
|
139
|
+
/**
|
140
|
+
* Obtain document path elements from DocumentReference
|
141
|
+
*/
|
142
|
+
export const docPathElements = (doc) => {
|
143
|
+
const parentPath = [];
|
144
|
+
let cursor = doc.parent.parent;
|
145
|
+
while (cursor) {
|
146
|
+
parentPath.push({ id: cursor.id, collection: cursor.parent.id });
|
147
|
+
cursor = cursor.parent.parent;
|
148
|
+
}
|
149
|
+
return [{ collection: doc.parent.id, id: doc.id }, ...parentPath];
|
150
|
+
};
|
151
|
+
// OPTIMIZE: cache query
|
152
|
+
export const toFirestoreQuery = (db, query) => {
|
153
|
+
let base;
|
154
|
+
switch (query.base.kind) {
|
155
|
+
case 'collection':
|
156
|
+
base = db.collection(collectionPath(query.base.collection, query.base.parentId));
|
157
|
+
break;
|
158
|
+
case 'collectionGroup':
|
159
|
+
base = db.collectionGroup(query.base.collection.name);
|
160
|
+
break;
|
161
|
+
case 'extends':
|
162
|
+
base = toFirestoreQuery(db, query.base.query);
|
163
|
+
break;
|
164
|
+
default:
|
165
|
+
base = assertNever(query.base);
|
166
|
+
}
|
167
|
+
return (query.constraints?.reduce((q, constraint) => {
|
168
|
+
switch (constraint.kind) {
|
169
|
+
case 'where':
|
170
|
+
return q.where(toFirestoreFilter(constraint.filter));
|
171
|
+
case 'orderBy':
|
172
|
+
return q.orderBy(constraint.field, constraint.direction);
|
173
|
+
case 'limit':
|
174
|
+
return q.limit(constraint.limit);
|
175
|
+
case 'limitToLast':
|
176
|
+
return q.limitToLast(constraint.limit);
|
177
|
+
case 'offset':
|
178
|
+
return q.offset(constraint.offset);
|
179
|
+
case 'startAt': {
|
180
|
+
const { cursor } = constraint;
|
181
|
+
return q.startAt(...cursor);
|
182
|
+
}
|
183
|
+
case 'startAfter': {
|
184
|
+
const { cursor } = constraint;
|
185
|
+
return q.startAfter(...cursor);
|
186
|
+
}
|
187
|
+
case 'endAt': {
|
188
|
+
const { cursor } = constraint;
|
189
|
+
return q.endAt(...cursor);
|
190
|
+
}
|
191
|
+
case 'endBefore': {
|
192
|
+
const { cursor } = constraint;
|
193
|
+
return q.endBefore(...cursor);
|
194
|
+
}
|
195
|
+
default:
|
196
|
+
return assertNever(constraint);
|
197
|
+
}
|
198
|
+
}, base) ?? base);
|
199
|
+
};
|
200
|
+
export const toFirestoreFilter = (expr) => {
|
201
|
+
switch (expr.kind) {
|
202
|
+
case 'where':
|
203
|
+
return Filter.where(expr.fieldPath, expr.opStr, expr.value);
|
204
|
+
case 'and':
|
205
|
+
return Filter.and(...expr.filters.map(toFirestoreFilter));
|
206
|
+
case 'or':
|
207
|
+
return Filter.or(...expr.filters.map(toFirestoreFilter));
|
208
|
+
default:
|
209
|
+
return assertNever(expr);
|
210
|
+
}
|
211
|
+
};
|
212
|
+
/**
|
213
|
+
* A query offset constraint
|
214
|
+
*/
|
215
|
+
export const offset = (offset) => ({ kind: 'offset', offset });
|
package/package.json
ADDED
@@ -0,0 +1,51 @@
|
|
1
|
+
{
|
2
|
+
"name": "@firestore-repository/google-cloud-firestore",
|
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
|
+
"@google-cloud/firestore": "^7.10.0",
|
13
|
+
"firestore-repository": "0.1.0"
|
14
|
+
},
|
15
|
+
"exports": {
|
16
|
+
".": {
|
17
|
+
"import": {
|
18
|
+
"types": "./build/esm/index.d.ts",
|
19
|
+
"default": "./build/esm/index.js"
|
20
|
+
}
|
21
|
+
},
|
22
|
+
"./*": {
|
23
|
+
"import": {
|
24
|
+
"types": "./build/esm/*.d.ts",
|
25
|
+
"default": "./build/esm/*.js"
|
26
|
+
}
|
27
|
+
}
|
28
|
+
},
|
29
|
+
"files": [
|
30
|
+
"build",
|
31
|
+
"!**/*.tsbuildinfo"
|
32
|
+
],
|
33
|
+
"keywords": [
|
34
|
+
"firestore",
|
35
|
+
"orm",
|
36
|
+
"database",
|
37
|
+
"repository",
|
38
|
+
"firebase",
|
39
|
+
"firebase-admin",
|
40
|
+
"google-cloud"
|
41
|
+
],
|
42
|
+
"author": "Naoto Ikeno <ikenox@gmail.com>",
|
43
|
+
"license": "MIT",
|
44
|
+
"publishConfig": {
|
45
|
+
"access": "public"
|
46
|
+
},
|
47
|
+
"scripts": {
|
48
|
+
"typecheck": "tsc --noEmit",
|
49
|
+
"build": "rm -rf build/ && tsc -b tsconfig.build.json"
|
50
|
+
}
|
51
|
+
}
|