From ba23e69ec1d6f866ae2b6c3b41a52d4b05d781e5 Mon Sep 17 00:00:00 2001 From: Marshall Polaris Date: Fri, 19 Aug 2022 17:27:47 -0700 Subject: [PATCH] Fix stuff to not prematurely initialize Firebase when imported --- functions/src/api.ts | 11 ++++------- functions/src/create-group.ts | 6 +++--- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/functions/src/api.ts b/functions/src/api.ts index e9a488c2..7440f16a 100644 --- a/functions/src/api.ts +++ b/functions/src/api.ts @@ -23,13 +23,8 @@ type JwtCredentials = { kind: 'jwt'; data: admin.auth.DecodedIdToken } type KeyCredentials = { kind: 'key'; data: string } type Credentials = JwtCredentials | KeyCredentials -const auth = admin.auth() -const firestore = admin.firestore() -const privateUsers = firestore.collection( - 'private-users' -) as admin.firestore.CollectionReference - export const parseCredentials = async (req: Request): Promise => { + const auth = admin.auth() const authHeader = req.get('Authorization') if (!authHeader) { throw new APIError(403, 'Missing Authorization header.') @@ -57,6 +52,8 @@ export const parseCredentials = async (req: Request): Promise => { } export const lookupUser = async (creds: Credentials): Promise => { + const firestore = admin.firestore() + const privateUsers = firestore.collection('private-users') switch (creds.kind) { case 'jwt': { if (typeof creds.data.user_id !== 'string') { @@ -70,7 +67,7 @@ export const lookupUser = async (creds: Credentials): Promise => { if (privateUserQ.empty) { throw new APIError(403, `No private user exists with API key ${key}.`) } - const privateUser = privateUserQ.docs[0].data() + const privateUser = privateUserQ.docs[0].data() as PrivateUser return { uid: privateUser.id, creds: { privateUser, ...creds } } } default: diff --git a/functions/src/create-group.ts b/functions/src/create-group.ts index a9626916..71c6bd64 100644 --- a/functions/src/create-group.ts +++ b/functions/src/create-group.ts @@ -21,6 +21,7 @@ const bodySchema = z.object({ }) export const creategroup = newEndpoint({}, async (req, auth) => { + const firestore = admin.firestore() const { name, about, memberIds, anyoneCanJoin } = validate( bodySchema, req.body @@ -67,7 +68,7 @@ export const creategroup = newEndpoint({}, async (req, auth) => { return { status: 'success', group: group } }) -const getSlug = async (name: string) => { +export const getSlug = async (name: string) => { const proposedSlug = slugify(name) const preexistingGroup = await getGroupFromSlug(proposedSlug) @@ -75,9 +76,8 @@ const getSlug = async (name: string) => { return preexistingGroup ? proposedSlug + '-' + randomString() : proposedSlug } -const firestore = admin.firestore() - export async function getGroupFromSlug(slug: string) { + const firestore = admin.firestore() const snap = await firestore .collection('groups') .where('slug', '==', slug)