kossnocorp / typesaurus

🦕 Type-safe TypeScript-first ODM for Firestore
https://typesaurus.com
415 stars 36 forks source link

How can I choose a custom database ID instead of the (default) one? #130

Open mailaneel opened 7 months ago

mailaneel commented 7 months ago

Reopening #126

databaseId is second param to getFirestore, without this it always uses (default) database https://github.com/kossnocorp/typesaurus/blob/7976747ddfa726350d751e7b31894d31f76f3646/src/adapter/admin/firebase.mjs#L15

kossnocorp commented 7 months ago

Hey! You can configure it using the options schema argument: https://typesaurus.com/api/schema/#app

mailaneel commented 7 months ago

@kossnocorp apologies for raising this again, I tried using the schema option like you have suggested, but it didn't work as expected.

Below is the logic used in typesaurus to get firestore, when we pass { app: 'some-name' } assuming some-name is the name of the firestore database. we are getting app instance with different name, but firestore is still using default database (getFirestore logic added below). Also I don't see a option to pass to initializeApp

export function firestore(options) {
  const appName = options?.server?.app || options?.app;
  const app = getApp(appName);

  if (options?.server?.preferRest) {
    return initializeFirestore(app, {
      preferRest: options?.server?.preferRest,
    });
  } else {
    return getFirestore(app);
  }
}

getFirestore from firebase.js

export function getFirestore(app: App, databaseId: string): Firestore;

export function getFirestore(
  appOrDatabaseId?: App | string,
  optionalDatabaseId?: string
): Firestore {
  const app: App = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp();
  const databaseId =
    (typeof appOrDatabaseId === 'string' ? appOrDatabaseId : optionalDatabaseId) || DEFAULT_DATABASE_ID;
  const firebaseApp: FirebaseApp = app as FirebaseApp;
  const firestoreService = firebaseApp.getOrInitService(
    'firestore', (app) => new FirestoreService(app));
  return firestoreService.getDatabase(databaseId);
}
kossnocorp commented 6 months ago

Hey, sorry that it doesn't work for you. Let me reopen the issue, add tests and fix it.

ecaroth commented 3 months ago

I had this need myself, just submitted a PR that fixes it @kossnocorp https://github.com/kossnocorp/typesaurus/pull/139

aaaaahaaaaa commented 2 months ago

@kossnocorp Can we get a bit of love on this issue and get this merged and released? Not being able to select a different DB is a hard blocker for many I'm sure. This feature has been GA in Firestore since February.