Skip to content

Commit

Permalink
feat(logs): use consola for logs
Browse files Browse the repository at this point in the history
This allows to control the level of logs with `CONSOLA_LEVEL=5 pnpm run dev`
  • Loading branch information
posva committed Jul 17, 2023
1 parent 7c21690 commit f802558
Show file tree
Hide file tree
Showing 13 changed files with 118 additions and 123 deletions.
1 change: 1 addition & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default defineBuildConfig({
'firebase-admin/auth',
'firebase-functions',
'firebase-functions/params',
'consola',
],

rollup: {
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"vue-demi": "latest"
},
"peerDependencies": {
"consola": "^3.2.3",
"firebase": "^9.0.0 || ^10.0.0",
"vue": "^2.7.0 || ^3.2.0"
},
Expand All @@ -76,13 +77,17 @@
},
"@vue/composition-api": {
"optional": true
},
"consola": {
"optional": true
}
},
"devDependencies": {
"@vitest/coverage-v8": "^0.33.0",
"@vue/runtime-core": "^3.3.4",
"@vue/test-utils": "^2.4.0",
"chalk": "^5.3.0",
"consola": "^3.2.3",
"conventional-changelog-cli": "^2.0.34",
"enquirer": "^2.3.6",
"execa": "^7.1.1",
Expand Down
6 changes: 6 additions & 0 deletions packages/nuxt/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
// explicitly externalize consola since Nuxt has it
externals: ['consola'],
})
13 changes: 6 additions & 7 deletions packages/nuxt/src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import type {
App as FirebaseAdminApp,
} from 'firebase-admin/app'
import { markRaw } from 'vue'
import { consola } from 'consola'
import type { NuxtVueFireAppCheckOptions } from './runtime/app-check'
import { log } from './runtime/logging'

export interface VueFireNuxtModuleOptions {
/**
Expand Down Expand Up @@ -63,6 +63,8 @@ export interface VueFireNuxtModuleOptions {
auth?: boolean
}

const logger = consola.withTag('nuxt-vuefire module')

export default defineNuxtModule<VueFireNuxtModuleOptions>({
meta: {
name: 'vuefire',
Expand Down Expand Up @@ -126,8 +128,7 @@ export default defineNuxtModule<VueFireNuxtModuleOptions>({

if (options.auth) {
if (nuxt.options.ssr && !hasServiceAccount) {
log(
'warn',
logger.warn(
'You activated both SSR and auth but you are not providing a service account for the admin SDK. See https://vuefire.vuejs.org/nuxt/getting-started.html#configuring-the-admin-sdk.'
)
}
Expand All @@ -138,8 +139,7 @@ export default defineNuxtModule<VueFireNuxtModuleOptions>({
if (hasServiceAccount) {
addPlugin(resolve(runtimeDir, 'app-check/plugin.server'))
} else if (nuxt.options.ssr) {
log(
'warn',
logger.warn(
'You activated both SSR and app-check but you are not providing a service account for the admin SDK. See https://vuefire.vuejs.org/nuxt/getting-started.html#configuring-the-admin-sdk.'
)
}
Expand Down Expand Up @@ -192,8 +192,7 @@ export default defineNuxtModule<VueFireNuxtModuleOptions>({
// we start the admin app before the regular app so we can have access to the user uid everywhere
if (options.admin || nuxt.options.ssr) {
if (!nuxt.options.ssr) {
log(
'warn',
logger.warn(
'The "admin" option is only used during SSR. You should reenable SSR to use it or remove it if you are not doing SSR or SSG.'
)
}
Expand Down
10 changes: 5 additions & 5 deletions packages/nuxt/src/runtime/app/plugin.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { deleteApp, type FirebaseApp, initializeApp } from 'firebase/app'
import { type User } from 'firebase/auth'
import { DecodedIdToken } from 'firebase-admin/auth'
import { LRUCache } from 'lru-cache'
import { log } from '../logging'
import { logger } from '../logging'
import { DECODED_ID_TOKEN_SYMBOL } from '../constants'
import { defineNuxtPlugin, useAppConfig } from '#app'

Expand Down Expand Up @@ -36,21 +36,21 @@ export default defineNuxtPlugin((nuxtApp) => {

let firebaseApp: FirebaseApp | undefined

// log('debug', 'initializing app with', appConfig.firebaseConfig)
// logger.debug('initializing app with', appConfig.firebaseConfig)
if (uid) {
firebaseApp = appCache.get(uid)
if (!firebaseApp) {
const randomId = Math.random().toString(36).slice(2)
// TODO: do we need a randomId?
const appName = `auth:${uid}:${randomId}`

log('debug', '👤 creating new app', appName)
logger.debug('👤 creating new app', appName)

appCache.set(uid, initializeApp(appConfig.firebaseConfig, appName))
firebaseApp = appCache.get(uid)!
// console.time('token')
} else {
log('debug', '👤 reusing authenticated app', firebaseApp.name)
logger.debug('👤 reusing authenticated app', firebaseApp.name)
}
} else {
// TODO: is this safe? should we create a new one everytime
Expand All @@ -59,7 +59,7 @@ export default defineNuxtPlugin((nuxtApp) => {
}
firebaseApp = appCache.get('')!
// anonymous session, just create a new app
log('debug', '🥸 anonymous session')
logger.debug('🥸 anonymous session')
}

return {
Expand Down
13 changes: 6 additions & 7 deletions packages/nuxt/src/runtime/auth/api.session-verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
setResponseStatus,
} from 'h3'
import { getAdminApp } from 'vuefire/server'
import { log } from '../logging'
import { logger } from '../logging'

/**
* Setups an API endpoint to be used by the client to mint a cookie based auth session.
Expand All @@ -17,11 +17,11 @@ export default defineEventHandler(async (event) => {
assertMethod(event, 'POST')
const { token } = await readBody<{ token?: string }>(event)

log('debug', 'Getting the admin app')
logger.debug('Getting the admin app')
const adminApp = getAdminApp({}, 'session-verification')
const adminAuth = getAdminAuth(adminApp)

log('debug', 'read idToken from Authorization header', token)
logger.debug(token ? 'Verifying the token' : 'Deleting the session cookie')
const verifiedIdToken = token ? await adminAuth.verifyIdToken(token) : null

if (verifiedIdToken) {
Expand All @@ -31,11 +31,10 @@ export default defineEventHandler(async (event) => {
const cookie = await adminAuth
.createSessionCookie(token!, { expiresIn: AUTH_COOKIE_MAX_AGE })
.catch((e: any) => {
log('error', 'Error minting the cookie -', e.message)
log('error', e)
logger.error('Error minting the cookie', e)
})
if (cookie) {
// log('debug', `minted a session cookie for user ${verifiedIdToken.uid}`)
// logger.debug(`minted a session cookie for user ${verifiedIdToken.uid}`)
setCookie(event, AUTH_COOKIE_NAME, cookie, {
maxAge: AUTH_COOKIE_MAX_AGE,
secure: true,
Expand All @@ -51,7 +50,7 @@ export default defineEventHandler(async (event) => {
}
}
} else {
// log('debug', 'deleting the session cookie')
// logger.debug('deleting the session cookie')
deleteCookie(event, AUTH_COOKIE_NAME)
setResponseStatus(event, 204)
}
Expand Down
8 changes: 5 additions & 3 deletions packages/nuxt/src/runtime/auth/plugin.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { FirebaseApp } from 'firebase/app'
import type { App as AdminApp } from 'firebase-admin/app'
import { VueFireAuthServer } from 'vuefire/server'
import { DECODED_ID_TOKEN_SYMBOL, UserSymbol } from '../constants'
import { log } from '../logging'
import { logger } from '../logging'
import { defineNuxtPlugin, useRequestEvent } from '#app'

/**
Expand All @@ -30,7 +30,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
const customToken = await adminAuth
.createCustomToken(uid)
.catch((err) => {
log('error', 'Error creating custom token', err)
logger.error('Error creating custom token', err)
return null
})
// console.timeLog('token', `got token for ${user.uid}`)
Expand All @@ -50,12 +50,14 @@ export default defineNuxtPlugin(async (nuxtApp) => {
UserSymbol as unknown as string
] = user
// expose the user to requests
// FIXME: should be doable in nitro server routes too
// use addServerPlugin
event.context.user = user
// Hydrates the user
nuxtApp.payload.vuefireUser = user?.toJSON()
}

// log('debug', 'setting up user for app', firebaseApp.name, user?.uid)
// logger.debug('setting up user for app', firebaseApp.name, user?.uid)

// provide the user data to the app during ssr
VueFireAuthServer(firebaseApp, nuxtApp.vueApp, auth.currentUser)
Expand Down
37 changes: 16 additions & 21 deletions packages/nuxt/src/runtime/logging.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
export type LogType = 'debug' | 'info' | 'warn' | 'error' | 'trace' | 'log'
import { consola as consolaBase } from 'consola'
export type { LogType } from 'consola'

// TODO: allow disabling logs with some env variables
const nuxtVueFireConsola = consolaBase.withTag('nuxt-vuefire')

export function log(type: LogType, ...args: any[]): void
export function log(...args: any[]): void
export function log(...args: unknown[]): void {
const [typeOrLog, ...rest] = args
if (isLogType(typeOrLog)) {
console[typeOrLog]('[nuxt-vuefire]:', ...rest)
} else {
console.log('[nuxt-vuefire]:', ...args)
}
}
export { nuxtVueFireConsola as logger }

function isLogType(logType: unknown): logType is LogType {
return (
logType === 'debug' ||
logType === 'info' ||
logType === 'warn' ||
logType === 'error' ||
logType === 'trace'
)
}
// run this to have more levels of logging
// https://github.com/unjs/consola#log-level
// CONSOLA_LEVEL=5 nr dev

// NOTE: used to test
// nuxtVueFireConsola.trace('trace', 'i am a test')
// nuxtVueFireConsola.debug('debug', 'i am a test')
// nuxtVueFireConsola.log('log', 'i am a test')
// nuxtVueFireConsola.info('info', 'i am a test')
// nuxtVueFireConsola.success('success', 'i am a test')
// nuxtVueFireConsola.warn('warn', 'i am a test')
// nuxtVueFireConsola.error('error', 'i am a test', new Error('haha'))

0 comments on commit f802558

Please sign in to comment.