Skip to content

Commit

Permalink
add status codes and event methods to log requests
Browse files Browse the repository at this point in the history
This commit moves the logRequestLine function into a separate file and adds
status codes and event methods. It grabs both get and post requests
  • Loading branch information
EvilGenius13 committed Oct 9, 2024
1 parent ef08e31 commit 4e3e92c
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 24 deletions.
38 changes: 38 additions & 0 deletions packages/theme/src/cli/utilities/log-request-line.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {timestampDateFormat} from '../constants.js'
import {Response as CliKitResponse} from '@shopify/cli-kit/node/http'
import {outputContent, outputInfo, outputToken} from '@shopify/cli-kit/node/output'
import {H3Event} from 'h3'

const CHARACTER_TRUNCATION_LIMIT = 80

export function logRequestLine(event: H3Event, response: CliKitResponse | Response) {
const truncatedPath =
event.path.length > CHARACTER_TRUNCATION_LIMIT
? `${event.path.substring(0, CHARACTER_TRUNCATION_LIMIT)}...`
: event.path
const serverTiming = response.headers.get('server-timing')
const requestDuration = serverTiming?.match(/cfRequestDuration;dur=([\d.]+)/)?.[1]
const durationString = requestDuration ? `${Math.round(Number(requestDuration))}ms` : ''

const statusColor = getColorizeStatus(response.status)

const eventMethodAligned = event.method.padStart(6)

outputInfo(
outputContent`• ${timestampDateFormat.format(new Date())} Request ${outputToken.raw(
'»',
)} ${eventMethodAligned} ${truncatedPath} ${statusColor(String(response.status))} ${outputToken.gray(
`${durationString}`,
)}`,
)
}

function getColorizeStatus(status: number) {
if (status < 300) {
return outputToken.green
} else if (status < 400) {
return outputToken.yellow
} else {
return outputToken.errorText
}
}
23 changes: 2 additions & 21 deletions packages/theme/src/cli/utilities/theme-environment/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@ import {getProxyStorefrontHeaders, patchRenderingResponse} from './proxy.js'
import {getInMemoryTemplates, injectHotReloadScript} from './hot-reload/server.js'
import {render} from './storefront-renderer.js'
import {getExtensionInMemoryTemplates} from '../theme-ext-environment/theme-ext-server.js'
import {timestampDateFormat} from '../../constants.js'
import {defineEventHandler, getCookie, H3Event, setResponseHeader, setResponseStatus, type H3Error} from 'h3'
import {logRequestLine} from '../log-request-line.js'
import {defineEventHandler, getCookie, setResponseHeader, setResponseStatus, type H3Error} from 'h3'
import {renderError, renderFatalError} from '@shopify/cli-kit/node/ui'
import {outputContent, outputInfo, outputToken} from '@shopify/cli-kit/node/output'
import {AbortError} from '@shopify/cli-kit/node/error'
import type {Response} from '@shopify/cli-kit/node/http'
import type {Theme} from '@shopify/cli-kit/node/themes/types'
import type {DevServerContext} from './types.js'

const CHARACTER_TRUNCATION_LIMIT = 80

export function getHtmlHandler(theme: Theme, ctx: DevServerContext) {
return defineEventHandler((event) => {
const [browserPathname = '/', browserSearch = ''] = event.path.split('?')
Expand Down Expand Up @@ -68,22 +65,6 @@ export function getHtmlHandler(theme: Theme, ctx: DevServerContext) {
})
}

function logRequestLine(event: H3Event, response: Response) {
const truncatedPath =
event.path.length > CHARACTER_TRUNCATION_LIMIT
? `${event.path.substring(0, CHARACTER_TRUNCATION_LIMIT)}...`
: event.path
const serverTiming = response.headers.get('server-timing')
const requestDuration = serverTiming?.match(/cfRequestDuration;dur=([\d.]+)/)?.[1]
const durationString = requestDuration ? `${Math.round(Number(requestDuration))}ms` : ''

outputInfo(
outputContent`• ${timestampDateFormat.format(new Date())} Request ${outputToken.raw('»')} ${outputToken.gray(
`${event.method} ${truncatedPath} ${durationString}`,
)}`,
)
}

function getErrorPage(options: {title: string; header: string; message: string; code: string}) {
const html = String.raw

Expand Down
25 changes: 25 additions & 0 deletions packages/theme/src/cli/utilities/theme-environment/proxy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {buildCookies} from './storefront-renderer.js'
import {logRequestLine} from '../log-request-line.js'
import {renderWarning} from '@shopify/cli-kit/node/ui'
import {
defineEventHandler,
Expand Down Expand Up @@ -85,6 +86,20 @@ export function canProxyRequest(event: H3Event) {
return Boolean(extension) || acceptsType !== '*/*'
}

function shouldLog(event: H3Event) {
const ignoredPathPrefixes = [EXTENSION_CDN_PREFIX, VANITY_CDN_PREFIX, '/checkouts', '/payments']
const ignoredExtensions = ['.js', '.css', '.json', '.map']

if (ignoredPathPrefixes.some((prefix) => event.path.startsWith(prefix))) return false

const [pathname] = event.path.split('?') as [string]
const extension = extname(pathname)

if (ignoredExtensions.includes(extension)) return false

return true
}

function getStoreFqdnForRegEx(ctx: DevServerContext) {
return ctx.session.storeFqdn.replaceAll('.', '\\.')
}
Expand Down Expand Up @@ -254,6 +269,16 @@ function proxyStorefrontRequest(event: H3Event, ctx: DevServerContext) {
redirect: 'manual',
},
async onResponse(event, response) {
if (
!event.path.startsWith(EXTENSION_CDN_PREFIX) &&
!event.path.startsWith(VANITY_CDN_PREFIX) &&
!event.path.endsWith('.js')
) {
if (shouldLog(event)) {
logRequestLine(event, response)
}
}

patchProxiedResponseHeaders(ctx, event, response)

const fileName = url.pathname.split('/').at(-1)
Expand Down
4 changes: 1 addition & 3 deletions packages/theme/src/cli/utilities/theme-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,6 @@ function dirPath(filePath: string) {

function outputSyncResult(action: 'update' | 'delete', fileKey: string): void {
outputInfo(
outputContent`• ${timestampDateFormat.format(new Date())} Synced ${outputToken.raw('»')} ${outputToken.gray(
`${action} ${fileKey}`,
)}`,
outputContent`• ${timestampDateFormat.format(new Date())} Synced ${outputToken.raw('»')} ${action} ${fileKey}`,
)
}

0 comments on commit 4e3e92c

Please sign in to comment.