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

Seperate firebase from accounts.ts to firebase.ts #1638

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
124 changes: 124 additions & 0 deletions src/lib/firebase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import metrics from "../../metrics";
import { FieldPath, getFirestore, WhereFilterOp } from 'firebase-admin/firestore'
import { lazy } from "./utils/lazy";
import { initializeApp } from "firebase-admin/app";
import admin from 'firebase-admin'

const app = lazy(() => {
if (admin.apps.length === 0) {
return initializeApp({
credential: admin.credential.cert(JSON.parse(Buffer.from(import.meta.env.FIREBASE_CREDENTIAL, 'base64').toString()))
})
} else {
return admin.apps[0]!
}
})

export const firestore = lazy(() => {
const firestore = getFirestore(app)
try {
firestore.settings({ preferRest: true })
} catch (error) {
// Catch cursed "Firestore has already been initialized" error
// console.error(error)
}
return firestore
})

const timedOperation = async (metricKey: string, callback: Function) => {
const startTime = new Date().getTime();
const result = await callback();
const endTime = (new Date().getTime()) - startTime;

metrics.timing(metricKey, endTime);
return result;
}

export const deleteDocument = async (path: string, documentId: string): Promise<void> => {
const metricKey = "database.delete";
try {
await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).delete());

metrics.increment(`${metricKey}.success`, 1);
} catch (error) {
console.error(`Failed to delete ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
}

export const addDocument = async (path: string, fields: any): Promise<admin.firestore.DocumentReference<admin.firestore.DocumentData>> => {
const metricKey = "database.add";
try {
const data = await timedOperation(metricKey, async () => await firestore.collection(path).add(fields));

metrics.increment(`${metricKey}.success`, 1);
return data;
} catch (error) {
console.error(`Failed to add document into ${path}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
return {} as any;
}

export const getDocument = async (path: string, documentId: string): Promise<admin.firestore.DocumentSnapshot<admin.firestore.DocumentData>> => {
const metricKey = "database.get";
try {
const data = await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).get());

metrics.increment(`${metricKey}.success`, 1);
return data;
} catch (error) {
console.error(`Failed to get document ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
return {} as any;
}

export const updateDocument = async (path: string, documentId: string, fields: any): Promise<void> => {
const metricKey = "database.update";
try {
await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).update(fields));

metrics.increment(`${metricKey}.success`, 1);
} catch (error) {
console.error(`Failed to update ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
}

export const setDocument = async (path: string, documentId: string, fields: any): Promise<void> => {
const metricKey = "database.set";
try {
await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).set(fields));

metrics.increment(`${metricKey}.success`, 1);
} catch (error) {
console.error(`Failed to set document ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
}

type WhereQuery = [string | FieldPath, WhereFilterOp, string];
type WhereParam = string | WhereQuery;
export const findDocument = async (path: string, where: WhereParam[] | [WhereParam, WhereFilterOp, WhereParam], limit: number = 1): Promise<any> => {
const metricKey = "database.find";
try {
let collection: any = firestore.collection(path);
if (typeof where[0] === 'object') {
for (let condition of where) {
collection = collection.where(condition[0], condition[1], condition[2]);
}
} else {
collection = collection.where(where[0], where[1], where[2]);
}

const data = await timedOperation(metricKey, async () => await collection.limit(limit).get());

metrics.increment(`${metricKey}.success`, 1);
return data;
} catch (error) {
console.error(`Failed to find: `, error);
metrics.increment(`${metricKey}.error`, 1);
return {};
}
}
123 changes: 2 additions & 121 deletions src/lib/game-saving/account.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,11 @@
import type { AstroCookies } from 'astro'
import admin from 'firebase-admin'
import { initializeApp } from 'firebase-admin/app'
import { FieldPath, getFirestore, Timestamp, WhereFilterOp } from 'firebase-admin/firestore'
import { customAlphabet } from 'nanoid/async'
import { lazy } from '../utils/lazy'
import { generateGameName } from '../words'
import metrics from '../../../metrics'
import {Timestamp} from "firebase-admin/firestore";
import {addDocument, findDocument, getDocument, updateDocument} from "../firebase";

const numberid = customAlphabet('0123456789')

const app = lazy(() => {
if (admin.apps.length === 0) {
return initializeApp({
credential: admin.credential.cert(JSON.parse(Buffer.from(import.meta.env.FIREBASE_CREDENTIAL, 'base64').toString()))
})
} else {
return admin.apps[0]!
}
})
export const firestore = lazy(() => {
const firestore = getFirestore(app)
try {
firestore.settings({ preferRest: true })
} catch (error) {
// Catch cursed "Firestore has already been initialized" error
// console.error(error)
}
return firestore
})

export interface User {
id: string
createdAt: Timestamp
Expand Down Expand Up @@ -84,103 +61,7 @@ export interface SessionInfo {
user: User
}

const timedOperation = async (metricKey: string, callback: Function) => {
const startTime = new Date().getTime();
const result = await callback();
const endTime = (new Date().getTime()) - startTime;

metrics.timing(metricKey, endTime);
return result;
}

export const deleteDocument = async (path: string, documentId: string): Promise<void> => {
const metricKey = "database.delete";
try {
await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).delete());

metrics.increment(`${metricKey}.success`, 1);
} catch (error) {
console.error(`Failed to delete ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
}

export const addDocument = async (path: string, fields: any): Promise<admin.firestore.DocumentReference<admin.firestore.DocumentData>> => {
const metricKey = "database.add";
try {
const data = await timedOperation(metricKey, async () => await firestore.collection(path).add(fields));

metrics.increment(`${metricKey}.success`, 1);
return data;
} catch (error) {
console.error(`Failed to add document into ${path}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
return {} as any;
}

export const getDocument = async (path: string, documentId: string): Promise<admin.firestore.DocumentSnapshot<admin.firestore.DocumentData>> => {
const metricKey = "database.get";
try {
const data = await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).get());

metrics.increment(`${metricKey}.success`, 1);
return data;
} catch (error) {
console.error(`Failed to get document ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
return {} as any;
}

export const updateDocument = async (path: string, documentId: string, fields: any): Promise<void> => {
const metricKey = "database.update";
try {
await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).update(fields));

metrics.increment(`${metricKey}.success`, 1);
} catch (error) {
console.error(`Failed to update ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
}

export const setDocument = async (path: string, documentId: string, fields: any): Promise<void> => {
const metricKey = "database.set";
try {
await timedOperation(metricKey, async () => await firestore.collection(path).doc(documentId).set(fields));

metrics.increment(`${metricKey}.success`, 1);
} catch (error) {
console.error(`Failed to set document ${documentId}: `, error);
metrics.increment(`${metricKey}.error`, 1);
}
}

type WhereQuery = [string | FieldPath, WhereFilterOp, string];
type WhereParam = string | WhereQuery;
export const findDocument = async (path: string, where: WhereParam[] | [WhereParam, WhereFilterOp, WhereParam], limit: number = 1): Promise<any> => {
const metricKey = "database.find";
try {
let collection: any = firestore.collection(path);
if (typeof where[0] === 'object') {
for (let condition of where) {
collection = collection.where(condition[0], condition[1], condition[2]);
}
} else {
collection = collection.where(where[0], where[1], where[2]);
}

const data = await timedOperation(metricKey, async () => await collection.limit(limit).get());

metrics.increment(`${metricKey}.success`, 1);
return data;
} catch (error) {
console.error(`Failed to find: `, error);
metrics.increment(`${metricKey}.error`, 1);
return {};
}
}

export const getSession = async (cookies: AstroCookies): Promise<SessionInfo | null> => {
if (!cookies.has('sprigSession')) return null
Expand Down
Loading