firebase-rest-firestore 0.3.0 → 1.0.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/dist/esm/index.js DELETED
@@ -1,349 +0,0 @@
1
- import * as jose from "jose";
2
- // Firestore関連の定数
3
- const FIREBASE_PROJECT_ID = process.env.FIREBASE_PROJECT_ID;
4
- const FIREBASE_PRIVATE_KEY_ID = process.env.FIREBASE_PRIVATE_KEY_ID;
5
- const FIREBASE_PRIVATE_KEY = process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, "\n");
6
- const FIREBASE_CLIENT_EMAIL = process.env.FIREBASE_CLIENT_EMAIL;
7
- const FIREBASE_CLIENT_ID = process.env.FIREBASE_CLIENT_ID;
8
- const FIREBASE_CLIENT_CERT_URL = process.env.FIREBASE_CLIENT_CERT_URL;
9
- // サービスアカウント情報
10
- const serviceAccount = {
11
- type: "service_account",
12
- project_id: FIREBASE_PROJECT_ID,
13
- private_key_id: FIREBASE_PRIVATE_KEY_ID,
14
- private_key: FIREBASE_PRIVATE_KEY,
15
- client_email: FIREBASE_CLIENT_EMAIL,
16
- client_id: FIREBASE_CLIENT_ID,
17
- auth_uri: "https://accounts.google.com/o/oauth2/auth",
18
- token_uri: "https://oauth2.googleapis.com/token",
19
- auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
20
- client_x509_cert_url: FIREBASE_CLIENT_CERT_URL,
21
- };
22
- // Firestoreのベースパス
23
- const getFirestoreBasePath = (collectionName) => {
24
- const basePath = `https://firestore.googleapis.com/v1/projects/${FIREBASE_PROJECT_ID}/databases/(default)/documents`;
25
- return collectionName ? `${basePath}/${collectionName}` : basePath;
26
- };
27
- /**
28
- * JSの値をFirestore形式に変換する
29
- */
30
- function convertToFirestoreValue(value) {
31
- if (value instanceof Date) {
32
- return { timestampValue: value.toISOString() };
33
- }
34
- else if (typeof value === "string") {
35
- return { stringValue: value };
36
- }
37
- else if (typeof value === "number") {
38
- return Number.isInteger(value)
39
- ? { integerValue: value }
40
- : { doubleValue: value };
41
- }
42
- else if (typeof value === "boolean") {
43
- return { booleanValue: value };
44
- }
45
- else if (value === null || value === undefined) {
46
- return { nullValue: null };
47
- }
48
- else if (Array.isArray(value)) {
49
- return {
50
- arrayValue: {
51
- values: value.map(item => convertToFirestoreValue(item)),
52
- },
53
- };
54
- }
55
- else if (typeof value === "object") {
56
- const fields = Object.entries(value).reduce((acc, [key, val]) => ({
57
- ...acc,
58
- [key]: convertToFirestoreValue(val),
59
- }), {});
60
- return { mapValue: { fields } };
61
- }
62
- // デフォルトは文字列化
63
- return { stringValue: String(value) };
64
- }
65
- /**
66
- * Firestore形式からJSの値に変換する
67
- */
68
- function convertFromFirestoreValue(firestoreValue) {
69
- if ("stringValue" in firestoreValue) {
70
- return firestoreValue.stringValue;
71
- }
72
- else if ("integerValue" in firestoreValue) {
73
- return Number(firestoreValue.integerValue);
74
- }
75
- else if ("doubleValue" in firestoreValue) {
76
- return firestoreValue.doubleValue;
77
- }
78
- else if ("booleanValue" in firestoreValue) {
79
- return firestoreValue.booleanValue;
80
- }
81
- else if ("nullValue" in firestoreValue) {
82
- return null;
83
- }
84
- else if ("timestampValue" in firestoreValue) {
85
- return new Date(firestoreValue.timestampValue);
86
- }
87
- else if ("mapValue" in firestoreValue && firestoreValue.mapValue.fields) {
88
- return Object.entries(firestoreValue.mapValue.fields).reduce((acc, [key, val]) => ({
89
- ...acc,
90
- [key]: convertFromFirestoreValue(val),
91
- }), {});
92
- }
93
- else if ("arrayValue" in firestoreValue &&
94
- firestoreValue.arrayValue.values) {
95
- return firestoreValue.arrayValue.values.map(convertFromFirestoreValue);
96
- }
97
- return null;
98
- }
99
- /**
100
- * オブジェクトをFirestoreドキュメント形式に変換
101
- */
102
- function convertToFirestoreDocument(data) {
103
- return {
104
- fields: Object.entries(data).reduce((acc, [key, value]) => ({
105
- ...acc,
106
- [key]: convertToFirestoreValue(value),
107
- }), {}),
108
- };
109
- }
110
- /**
111
- * Firestoreドキュメントをオブジェクトに変換
112
- */
113
- function convertFromFirestoreDocument(doc) {
114
- if (!doc.fields)
115
- return { id: getDocumentId(doc.name) };
116
- const result = Object.entries(doc.fields).reduce((acc, [key, value]) => ({
117
- ...acc,
118
- [key]: convertFromFirestoreValue(value),
119
- }), {});
120
- return {
121
- ...result,
122
- id: getDocumentId(doc.name),
123
- };
124
- }
125
- /**
126
- * ドキュメントパスからIDを抽出
127
- */
128
- function getDocumentId(path) {
129
- if (!path)
130
- return "";
131
- const pathParts = path.split("/");
132
- return pathParts[pathParts.length - 1];
133
- }
134
- // JWT(JSON Web Token)を作成する関数
135
- async function createJWT(serviceAccount) {
136
- const now = Math.floor(Date.now() / 1000);
137
- const payload = {
138
- iss: serviceAccount.client_email,
139
- sub: serviceAccount.client_email,
140
- aud: "https://oauth2.googleapis.com/token",
141
- iat: now,
142
- exp: now + 3600, // 1時間後に期限切れ
143
- scope: "https://www.googleapis.com/auth/datastore",
144
- };
145
- try {
146
- // 秘密鍵をインポート
147
- const privateKey = await jose.importPKCS8(serviceAccount.private_key, "RS256");
148
- // JWTを作成
149
- const token = await new jose.SignJWT(payload)
150
- .setProtectedHeader({
151
- alg: "RS256",
152
- kid: serviceAccount.private_key_id,
153
- typ: "JWT",
154
- })
155
- .sign(privateKey);
156
- return token;
157
- }
158
- catch (error) {
159
- console.error("JWT作成エラー:", error);
160
- throw error;
161
- }
162
- }
163
- /**
164
- * Firestoreの認証トークンを取得する関数
165
- */
166
- export async function getFirestoreToken() {
167
- // トークンを取得するためのリクエスト
168
- const response = await fetch("https://oauth2.googleapis.com/token", {
169
- method: "POST",
170
- headers: {
171
- "Content-Type": "application/json",
172
- },
173
- body: JSON.stringify({
174
- grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
175
- assertion: await createJWT(serviceAccount),
176
- }),
177
- });
178
- const data = (await response.json());
179
- return data.access_token;
180
- }
181
- /**
182
- * Firestoreクライアントクラス
183
- */
184
- export class FirestoreClient {
185
- constructor() {
186
- this.token = null;
187
- this.tokenExpiry = 0;
188
- }
189
- /**
190
- * 認証トークンを取得(キャッシュあり)
191
- */
192
- async getToken() {
193
- const now = Date.now();
194
- // トークンが期限切れか未取得の場合は新しく取得
195
- if (!this.token || now >= this.tokenExpiry) {
196
- this.token = await getFirestoreToken();
197
- // 50分後に期限切れとする(実際は1時間)
198
- this.tokenExpiry = now + 50 * 60 * 1000;
199
- }
200
- return this.token;
201
- }
202
- /**
203
- * Firestoreにドキュメントを作成
204
- */
205
- async create(collectionName, data) {
206
- const url = getFirestoreBasePath(collectionName);
207
- const firestoreData = convertToFirestoreDocument(data);
208
- const token = await this.getToken();
209
- const response = await fetch(url, {
210
- method: "POST",
211
- headers: {
212
- "Content-Type": "application/json",
213
- Authorization: `Bearer ${token}`,
214
- },
215
- body: JSON.stringify(firestoreData),
216
- });
217
- if (!response.ok) {
218
- throw new Error(`Firestore API error: ${response.statusText}`);
219
- }
220
- const result = (await response.json());
221
- return convertFromFirestoreDocument(result);
222
- }
223
- /**
224
- * ドキュメントを取得
225
- */
226
- async get(collectionName, documentId) {
227
- const url = `${getFirestoreBasePath(collectionName)}/${documentId}`;
228
- const token = await this.getToken();
229
- const response = await fetch(url, {
230
- method: "GET",
231
- headers: {
232
- Authorization: `Bearer ${token}`,
233
- },
234
- });
235
- if (response.status === 404) {
236
- return null;
237
- }
238
- if (!response.ok) {
239
- throw new Error(`Firestore API error: ${response.statusText}`);
240
- }
241
- const result = (await response.json());
242
- return convertFromFirestoreDocument(result);
243
- }
244
- /**
245
- * ドキュメントを更新
246
- */
247
- async update(collectionName, documentId, data) {
248
- const url = `${getFirestoreBasePath(collectionName)}/${documentId}`;
249
- const firestoreData = convertToFirestoreDocument(data);
250
- const token = await this.getToken();
251
- const response = await fetch(url, {
252
- method: "PATCH",
253
- headers: {
254
- "Content-Type": "application/json",
255
- Authorization: `Bearer ${token}`,
256
- },
257
- body: JSON.stringify(firestoreData),
258
- });
259
- if (!response.ok) {
260
- throw new Error(`Firestore API error: ${response.statusText}`);
261
- }
262
- const result = (await response.json());
263
- return convertFromFirestoreDocument(result);
264
- }
265
- /**
266
- * ドキュメントを削除
267
- */
268
- async delete(collectionName, documentId) {
269
- const url = `${getFirestoreBasePath(collectionName)}/${documentId}`;
270
- const token = await this.getToken();
271
- const response = await fetch(url, {
272
- method: "DELETE",
273
- headers: {
274
- Authorization: `Bearer ${token}`,
275
- },
276
- });
277
- if (!response.ok) {
278
- throw new Error(`Firestore API error: ${response.statusText}`);
279
- }
280
- return true;
281
- }
282
- /**
283
- * コレクションのドキュメントを検索
284
- */
285
- async query(collectionName, options = {}) {
286
- const url = `${getFirestoreBasePath(collectionName)}:runQuery`;
287
- // クエリ構築
288
- const structuredQuery = {
289
- from: [{ collectionId: collectionName }],
290
- };
291
- // フィルター条件
292
- if (options.where && options.where.length > 0) {
293
- structuredQuery.where = {
294
- compositeFilter: {
295
- op: "AND",
296
- filters: options.where.map(condition => ({
297
- fieldFilter: {
298
- field: { fieldPath: condition.field },
299
- op: condition.op,
300
- value: convertToFirestoreValue(condition.value),
301
- },
302
- })),
303
- },
304
- };
305
- }
306
- // 並べ替え
307
- if (options.orderBy) {
308
- structuredQuery.orderBy = [
309
- {
310
- field: { fieldPath: options.orderBy },
311
- direction: "ASCENDING",
312
- },
313
- ];
314
- }
315
- // 制限
316
- if (options.limit) {
317
- structuredQuery.limit = options.limit;
318
- }
319
- // オフセット
320
- if (options.offset) {
321
- structuredQuery.offset = options.offset;
322
- }
323
- const token = await this.getToken();
324
- const response = await fetch(url, {
325
- method: "POST",
326
- headers: {
327
- "Content-Type": "application/json",
328
- Authorization: `Bearer ${token}`,
329
- },
330
- body: JSON.stringify({
331
- structuredQuery,
332
- }),
333
- });
334
- if (!response.ok) {
335
- throw new Error(`Firestore API error: ${response.statusText}`);
336
- }
337
- const results = (await response.json());
338
- return results
339
- .filter(item => item.document)
340
- .map(item => convertFromFirestoreDocument(item.document));
341
- }
342
- }
343
- // デフォルトのFirestoreクライアントインスタンス
344
- export const firestore = new FirestoreClient();
345
- // 後方互換性のための関数
346
- export async function saveToFirestore(collectionName, data) {
347
- const result = await firestore.create(collectionName, data);
348
- return { documentId: result.id, result };
349
- }