Skip to content

Commit

Permalink
Fix pagecontext function (#29)
Browse files Browse the repository at this point in the history
feat: better `pageContext` typing

fix: do not override user provided `pageContext` with universal one
  • Loading branch information
magne4000 authored Dec 9, 2024
1 parent 485759d commit bc2d921
Show file tree
Hide file tree
Showing 14 changed files with 169 additions and 100 deletions.
6 changes: 4 additions & 2 deletions packages/vike-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,13 @@ function startServer() {
You can define custom [pageContext](https://vike.dev/pageContext) properties:

```ts
import { type RuntimeAdapter } from 'vike-node/express';

app.use(
vike({
pageContext(req: IncomingMessage) {
pageContext(runtime: RuntimeAdapter) {
return {
user: req.user
user: runtime.req.user
}
}
})
Expand Down
8 changes: 4 additions & 4 deletions packages/vike-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@
"dependencies": {
"@brillout/picocolors": "^1.0.14",
"@nitedani/shrink-ray-current": "^4.3.0",
"@universal-middleware/core": "^0.3.2",
"@universal-middleware/compress": "^0.2.6",
"@universal-middleware/core": "^0.3.3",
"@universal-middleware/compress": "^0.2.8",
"@vercel/nft": "^0.26.5",
"esbuild": "^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0",
"resolve-from": "^5.0.0",
Expand All @@ -100,7 +100,7 @@
"hono": "^4.6.3",
"tsup": "^8.3.0",
"typescript": "^5.5.4",
"universal-middleware": "^0.5.3",
"universal-middleware": "^0.5.5",
"vike": "^0.4.198",
"vite": "^6.0.2"
},
Expand All @@ -109,4 +109,4 @@
],
"repository": "github:vikejs/vike-node",
"license": "MIT"
}
}
9 changes: 7 additions & 2 deletions packages/vike-node/src/runtime/types.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import type { IncomingMessage, ServerResponse } from 'http'
import type { RuntimeAdapterTarget } from '@universal-middleware/core'

export type HeadersProvided = Record<string, string | string[] | undefined> | Headers
export type VikeHttpResponse = Awaited<ReturnType<typeof import('vike/server').renderPage>>['httpResponse']
export type NextFunction = (err?: unknown) => void
export type VikeOptions<PlatformRequest = unknown> = {
pageContext?: ((req: PlatformRequest) => Record<string, any> | Promise<Record<string, any>>) | Record<string, any>

export type VikeOptions<T = unknown> = {
pageContext?:
| ((req: RuntimeAdapterTarget<T>) => Record<string, any> | Promise<Record<string, any>>)
| Record<string, any>
compress?: boolean | 'static'
static?: boolean | string | { root?: string; cache?: boolean }
onError?: (err: unknown) => void
}

export type ConnectMiddleware<
PlatformRequest extends IncomingMessage = IncomingMessage,
PlatformResponse extends ServerResponse = ServerResponse
Expand Down
27 changes: 15 additions & 12 deletions packages/vike-node/src/runtime/vike-handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import type { IncomingMessage, ServerResponse } from 'http'
import compressMiddlewareFactory from '@universal-middleware/compress'
import { type Get, type UniversalHandler, type UniversalMiddleware } from '@universal-middleware/core'
import {
type Get,
type RuntimeAdapter,
type UniversalHandler,
type UniversalMiddleware
} from '@universal-middleware/core'
import { renderPage as _renderPage } from 'vike/server'
import { assert } from '../utils/assert.js'
import { isVercel } from '../utils/isVercel.js'
Expand All @@ -9,22 +14,22 @@ import { globalStore } from './globalStore.js'
import type { ConnectMiddleware, VikeHttpResponse, VikeOptions } from './types.js'
import { parseHeaders } from './utils/header-utils.js'

async function renderPage({
async function renderPage<T extends RuntimeAdapter>({
url,
headers,
runtimeRequest,
options
}: {
url: string
headers: [string, string][]
runtimeRequest: unknown
options: VikeOptions
runtimeRequest: T
options: VikeOptions & { pageContextUniversal?: Record<string, any> }
}): Promise<VikeHttpResponse> {
let pageContextInit: Record<string, any> = {}
let pageContextInit: Record<string, any> = options.pageContextUniversal ?? {}
if (typeof options?.pageContext === 'function') {
pageContextInit = await options.pageContext(runtimeRequest)
Object.assign(pageContextInit, await options.pageContext(runtimeRequest))
} else if (options?.pageContext) {
pageContextInit = options.pageContext
Object.assign(pageContextInit, options.pageContext)
}

const pageContext = await _renderPage({
Expand Down Expand Up @@ -94,13 +99,11 @@ export const renderPageHandler = ((options?) => async (request, context, runtime
const response = await renderPage({
url: request.url,
headers: parseHeaders(request.headers),
runtimeRequest: runtime.adapter in runtime ? (runtime as any)[runtime.adapter] : request,
runtimeRequest: runtime,
options: {
...options,
pageContext: {
...pageContextInit,
...options?.pageContext
}
pageContextUniversal: pageContextInit,
pageContext: options?.pageContext
}
})

Expand Down
128 changes: 64 additions & 64 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions test/vike-node/.testRun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ function testRun(cmd: 'pnpm run dev' | 'pnpm run prod') {
expect(html).toContain('<h1>To-do List</h1>')
expect(html).toContain('<li>Buy milk</li>')
expect(html).toContain('<li>Buy strawberries</li>')
// provided through pageContext function
expect(html).toContain('x-runtime')
})

test('Add to-do item', async () => {
Expand Down
5 changes: 3 additions & 2 deletions test/vike-node/pages/index/+Page.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
export default Page

import type { Todo } from '@prisma/client'
import React, { useState } from 'react'
import { TodoList } from './TodoList'
import type { Todo } from '@prisma/client'

function Page({ todoItemsInitial }: { todoItemsInitial: Todo[] }) {
function Page({ todoItemsInitial, xRuntime }: { todoItemsInitial: Todo[]; xRuntime?: string }) {
return (
<>
<h1>To-do List</h1>
<TodoList todoItemsInitial={todoItemsInitial} />
<Counter />
{xRuntime}
</>
)
}
Expand Down
3 changes: 2 additions & 1 deletion test/vike-node/pages/index/+onBeforeRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const onBeforeRender: OnBeforeRenderAsync = async (pageContext): ReturnType<OnBe
return {
pageContext: {
pageProps: {
todoItemsInitial
todoItemsInitial,
xRuntime: pageContext.xRuntime
}
}
}
Expand Down
1 change: 1 addition & 0 deletions test/vike-node/renderer/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ declare global {
namespace Vike {
interface PageContext {
Page: Page
xRuntime?: string
pageProps?: PageProps
}
}
Expand Down
15 changes: 12 additions & 3 deletions test/vike-node/server/index-elysia.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Elysia } from 'elysia'
import { telefunc } from 'telefunc'
import vike from 'vike-node/elysia'
import vike, { RuntimeAdapter } from 'vike-node/elysia'
import { init } from '../database/todoItems'

startServer()

async function startServer() {
await init()
const app = new Elysia()
const app = new Elysia().state('xRuntime', 'x-runtime')

const port = process.env.PORT || 3000
app.post('/_telefunc', async (ctx) => {
Expand All @@ -26,6 +26,15 @@ async function startServer() {
ctx.set.headers['x-test'] = 'test'
})

app.get('/*', vike())
app.get(
'/*',
vike({
pageContext(runtime: RuntimeAdapter) {
return {
xRuntime: (runtime.elysia.store as { xRuntime: string }).xRuntime
}
}
})
)
app.listen(+port, () => console.log(`Server running at http://localhost:${port}`))
}
13 changes: 11 additions & 2 deletions test/vike-node/server/index-express.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from 'express'
import { telefunc } from 'telefunc'
import vike from 'vike-node/express'
import vike, { type RuntimeAdapter } from 'vike-node/express'
import { Worker } from 'worker_threads'
import { init } from '../database/todoItems.js'
import { two } from './shared-chunk.js'
Expand All @@ -21,10 +21,19 @@ async function startServer() {
res.status(statusCode).type(contentType).send(body)
})
app.use((req, res, next) => {
;(req as any).xRuntime = 'x-runtime'
res.set('x-test', 'test')
next()
})
app.use(vike())
app.use(
vike({
pageContext(runtime: RuntimeAdapter) {
return {
xRuntime: (runtime.req as any).xRuntime
}
}
})
)
const port = process.env.PORT || 3000
app.listen(port)
console.log(`Server running at http://localhost:${port}`)
Expand Down
18 changes: 16 additions & 2 deletions test/vike-node/server/index-fastify.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Error.stackTraceLimit = Infinity
import fastify from 'fastify'
import { telefunc } from 'telefunc'
import vike from 'vike-node/fastify'
import vike, { RuntimeAdapter } from 'vike-node/fastify'
import { Worker } from 'worker_threads'
import { init } from '../database/todoItems.js'
import { two } from './shared-chunk.js'
Expand All @@ -22,12 +22,26 @@ async function startServer() {
res.status(statusCode).type(contentType).send(body)
})

app.addHook('onRequest', (request, reply, done) => {
;(request.routeOptions.config as any).xRuntime = 'x-runtime'
done()
})

app.addHook('onSend', (request, reply, payload, done) => {
reply.header('x-test', 'test')
done()
})

app.all('/*', vike())
app.all(
'/*',
vike({
pageContext(runtime: RuntimeAdapter) {
return {
xRuntime: (runtime.fastify.request.routeOptions.config as any).xRuntime
}
}
})
)
const port = process.env.PORT || 3000
app.listen({ port: +port })
console.log(`Server running at http://localhost:${port}`)
Expand Down
15 changes: 12 additions & 3 deletions test/vike-node/server/index-h3.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createApp, createRouter, eventHandler, toNodeListener, toWebRequest } from 'h3'
import { createServer } from 'http'
import { createApp, createRouter, eventHandler, toNodeListener, toWebRequest } from 'h3'
import { telefunc } from 'telefunc'
import vike from 'vike-node/h3'
import vike, { RuntimeAdapter } from 'vike-node/h3'
import { init } from '../database/todoItems'

startServer()
Expand Down Expand Up @@ -38,11 +38,20 @@ async function startServer() {

app.use(
eventHandler((event) => {
event.context.xRuntime = 'x-runtime'
event.node.res.setHeader('x-test', 'test')
})
)

app.use(vike())
app.use(
vike({
pageContext(runtime: RuntimeAdapter) {
return {
xRuntime: runtime.h3.context.xRuntime
}
}
})
)

const server = createServer(toNodeListener(app)).listen(port)

Expand Down
19 changes: 16 additions & 3 deletions test/vike-node/server/index-hono.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { telefunc } from 'telefunc'
import vike from 'vike-node/hono'
import vike, { type RuntimeAdapter } from 'vike-node/hono'
import { init } from '../database/todoItems'

startServer()

async function startServer() {
await init()
const app = new Hono()
const app = new Hono<{
Variables: {
xRuntime: string
}
}>()
const port = process.env.PORT || 3000
app.post('/_telefunc', async (ctx) => {
const context = {}
Expand All @@ -23,11 +27,20 @@ async function startServer() {
})

app.use('*', async (ctx, next) => {
ctx.set('xRuntime', 'x-runtime')
await next()
ctx.header('x-test', 'test')
})

app.use(vike())
app.use(
vike({
pageContext(runtime: RuntimeAdapter) {
return {
xRuntime: runtime.hono.get('xRuntime')
}
}
})
)

serve(
{
Expand Down

0 comments on commit bc2d921

Please sign in to comment.