Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(server): dedupe api server code, make host configurable #9948

Merged
merged 26 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/adapters/fastify/web/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ export interface RedwoodFastifyWebOptions {
* Specify the URL to your API server.
* This can be a relative URL on the current domain (`/.redwood/functions`),
* in which case the `apiProxyTarget` option must be set,
* or a fully qualified URL (`https://api.redwood.horse`).
* or a fully-qualified URL (`https://api.redwood.horse`).
*
* Note: This should not include the path to the GraphQL Server.
**/
apiUrl?: string
/**
* The fully qualified URL to proxy requests to from apiUrl.
* Only valid when apiUrl is a relative URL.
* The fully-qualified URL to proxy requests to from `apiUrl`.
* Only valid when `apiUrl` is a relative URL.
*/
apiProxyTarget?: string

Expand Down
46 changes: 20 additions & 26 deletions packages/adapters/fastify/web/src/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,28 +21,19 @@ export async function redwoodFastifyWeb(
) {
const { redwoodOptions, flags } = resolveOptions(opts)

await fastify.register(fastifyUrlData)
fastify.register(fastifyUrlData)
fastify.register(fastifyStatic, { root: getPaths().web.dist })

// Serve prerendered files directly, instead of the index
const prerenderedFiles = await fg('**/*.html', {
cwd: getPaths().web.dist,
ignore: ['index.html', '200.html', '404.html'],
})

for (const prerenderedFile of prerenderedFiles) {
const [pathName] = prerenderedFile.split('.html')

fastify.get(`/${pathName}`, (_, reply) => {
reply.header('Content-Type', 'text/html; charset=UTF-8')
reply.sendFile(prerenderedFile)
// If `apiProxyTarget` is set, proxy requests from `apiUrl` to `apiProxyTarget`.
// In this case, `apiUrl` has to be relative; `resolveOptions` above throws if it's not
if (redwoodOptions.apiProxyTarget) {
fastify.register(httpProxy, {
prefix: redwoodOptions.apiUrl,
upstream: redwoodOptions.apiProxyTarget,
disableCache: true,
})
}

// Serve static assets
fastify.register(fastifyStatic, {
root: getPaths().web.dist,
})

// If `shouldRegisterApiUrl` is true, `apiUrl` has to be defined
// but TS doesn't know that so it complains about `apiUrl` being undefined
// in `fastify.all(...)` below. So we have to do this check for now
Expand All @@ -69,20 +60,23 @@ export async function redwoodFastifyWeb(
fastify.all(`${apiUrlWarningPath}*`, apiUrlHandler)
}

// If `apiProxyTarget` is set, proxy requests from `apiUrl` to `apiProxyTarget`.
// In this case, `apiUrl` has to be relative; `resolveOptions` above throws if it's not
if (redwoodOptions.apiProxyTarget) {
fastify.register(httpProxy, {
prefix: redwoodOptions.apiUrl,
upstream: redwoodOptions.apiProxyTarget,
disableCache: true,
// Serve prerendered files directly, instead of the index
const prerenderedFiles = await fg('**/*.html', {
cwd: getPaths().web.dist,
ignore: ['index.html', '200.html', '404.html'],
})

for (const prerenderedFile of prerenderedFiles) {
const [pathName] = prerenderedFile.split('.html')
fastify.get(`/${pathName}`, (_, reply) => {
reply.header('Content-Type', 'text/html; charset=UTF-8')
reply.sendFile(prerenderedFile)
})
}

// If `200.html` exists, the project has been prerendered.
// If it doesn't, fallback to the default (`index.html`)
const prerenderIndexPath = path.join(getPaths().web.dist, '200.html')

const fallbackIndexPath = fs.existsSync(prerenderIndexPath)
? '200.html'
: 'index.html'
Expand Down
61 changes: 61 additions & 0 deletions packages/api-server/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import {
build,
defaultBuildOptions,
defaultIgnorePatterns,
} from '../../buildDefaults.mjs'

// Build the package
await build({
entryPointOptions: {
ignore: [
...defaultIgnorePatterns,
'./src/bin.ts',
'./src/logFormatter/bin.ts',
'./src/types.ts',
'./src/watch.ts',
],
},
})

// Build the rw-server bin
await build({
buildOptions: {
...defaultBuildOptions,
banner: {
js: '#!/usr/bin/env node',
},
bundle: true,
entryPoints: ['./src/bin.ts'],
packages: 'external',
},
metafileName: 'meta.rwServer.json',
})

// Build the logFormatter bin
await build({
buildOptions: {
...defaultBuildOptions,
banner: {
js: '#!/usr/bin/env node',
},
bundle: true,
entryPoints: ['./src/logFormatter/bin.ts'],
outdir: './dist/logFormatter',
packages: 'external',
},
metafileName: 'meta.logFormatter.json',
})

// Build the watch bin
await build({
buildOptions: {
...defaultBuildOptions,
banner: {
js: '#!/usr/bin/env node',
},
bundle: true,
entryPoints: ['./src/watch.ts'],
packages: 'external',
},
metafileName: 'meta.watch.json',
})
65 changes: 12 additions & 53 deletions packages/api-server/dist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,70 +9,29 @@ describe('dist', () => {
expect(fs.existsSync(path.join(distPath, '__tests__'))).toEqual(false)
})

// The way this package was written, you can't just import it. It expects to be in a Redwood project.
it('fails if imported outside a Redwood app', async () => {
try {
await import(path.join(distPath, 'cliHandlers.js'))
} catch (e) {
expect(e.message).toMatchInlineSnapshot(
`"Could not find a "redwood.toml" file, are you sure you're in a Redwood project?"`
)
}
})
Tobbe marked this conversation as resolved.
Show resolved Hide resolved

it('exports CLI options and handlers', async () => {
it('exports CLI config', async () => {
const original_RWJS_CWD = process.env.RWJS_CWD

process.env.RWJS_CWD = path.join(
__dirname,
'src/__tests__/fixtures/redwood-app'
)

const mod = await import(
path.resolve(distPath, packageConfig.main.replace('dist/', ''))
)
const mod = await import(path.resolve(distPath, './cliConfig.js'))

expect(mod).toMatchInlineSnapshot(`
{
"apiCliOptions": {
"apiRootPath": {
"alias": [
"api-root-path",
"rootPath",
"root-path",
],
"coerce": [Function],
"default": "/",
"desc": "Root path where your api functions are served",
"type": "string",
},
"loadEnvFiles": {
"description": "Deprecated; env files are always loaded. This flag is a no-op",
"hidden": true,
"type": "boolean",
},
"port": {
"alias": "p",
"default": 8911,
"type": "number",
},
"socket": {
"type": "string",
},
"apiServerCLIConfig": {
"builder": [Function],
"command": "api",
"description": "Start a server for serving only the api side",
"handler": [Function],
},
"apiServerHandler": [Function],
"bothServerHandler": [Function],
"commonOptions": {
"port": {
"alias": "p",
"default": 8910,
"type": "number",
},
"socket": {
"type": "string",
},
"bothServerCLIConfig": {
"builder": [Function],
"description": "Start a server for serving both the api and web sides",
"handler": [Function],
},
"createServer": [Function],
}
`)

Expand All @@ -84,7 +43,7 @@ describe('dist', () => {
{
"rw-api-server-watch": "./dist/watch.js",
"rw-log-formatter": "./dist/logFormatter/bin.js",
"rw-server": "./dist/index.js",
"rw-server": "./dist/bin.js",
}
`)
})
Expand Down
35 changes: 26 additions & 9 deletions packages/api-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,40 @@
"directory": "packages/api-server"
},
"license": "MIT",
"main": "dist/cliHandlers",
"exports": {
".": {
"types": "./dist/cliConfig.d.ts",
"default": "./dist/cliConfig.js"
},
"./create-server": {
"types": "./dist/createServer.d.ts",
"default": "./dist/createServer.js"
},
"./fastify-api": {
"types": "./dist/plugins/api.d.ts",
"default": "./dist/plugins/api.js"
},
"./fastify-graphql": {
"types": "./dist/plugins/graphql.d.ts",
"default": "./dist/plugins/graphql.js"
},
Tobbe marked this conversation as resolved.
Show resolved Hide resolved
"./helpers": {
"types": "./dist/helpers.d.ts",
"default": "./dist/helpers.js"
},
"./package.json": "./package.json"
},
"types": "./dist/cliConfig.d.ts",
"bin": {
"rw-api-server-watch": "./dist/watch.js",
"rw-log-formatter": "./dist/logFormatter/bin.js",
"rw-server": "./dist/index.js"
"rw-server": "./dist/bin.js"
},
"files": [
"dist"
],
"scripts": {
"build": "yarn build:js && yarn build:types",
"build:js": "babel src -d dist --extensions \".js,.jsx,.ts,.tsx\"",
"build": "yarn node ./build.mjs && yarn build:types",
"build:pack": "yarn pack -o redwoodjs-api-server.tgz",
"build:types": "tsc --build --verbose tsconfig.build.json",
"build:watch": "nodemon --watch src --ext \"js,jsx,ts,tsx\" --ignore dist --exec \"yarn build && yarn fix:permissions\"",
Expand All @@ -29,16 +51,13 @@
"test:watch": "yarn test --watch"
},
"dependencies": {
"@babel/runtime-corejs3": "7.23.9",
Tobbe marked this conversation as resolved.
Show resolved Hide resolved
"@fastify/url-data": "5.4.0",
"@redwoodjs/context": "6.0.7",
"@redwoodjs/fastify-web": "6.0.7",
"@redwoodjs/project-config": "6.0.7",
"@redwoodjs/web-server": "6.0.7",
"ansi-colors": "4.1.3",
"chalk": "4.1.2",
"chokidar": "3.5.3",
"core-js": "3.35.1",
"dotenv-defaults": "5.0.2",
"fast-glob": "3.3.2",
"fast-json-parse": "1.0.3",
Expand All @@ -52,8 +71,6 @@
"yargs": "17.7.2"
},
"devDependencies": {
"@babel/cli": "7.23.9",
"@babel/core": "^7.22.20",
"@types/aws-lambda": "8.10.126",
"@types/lodash": "4.14.201",
"@types/qs": "6.9.11",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path'

import createFastifyInstance from '../fastify'
import withFunctions from '../plugins/withFunctions'
import { redwoodFastifyAPI } from '../plugins/api'

// Suppress terminal logging.
console.log = jest.fn()
Expand All @@ -21,14 +21,14 @@ afterAll(() => {

// Set up and teardown the fastify instance for each test.
let fastifyInstance: ReturnType<typeof createFastifyInstance>
let returnedFastifyInstance: Awaited<ReturnType<typeof withFunctions>>

beforeAll(async () => {
fastifyInstance = createFastifyInstance()

returnedFastifyInstance = await withFunctions(fastifyInstance, {
port: 8911,
apiRootPath: '/',
fastifyInstance.register(redwoodFastifyAPI, {
redwood: {
loadUserConfig: true,
},
})

await fastifyInstance.ready()
Expand All @@ -38,28 +38,14 @@ afterAll(async () => {
await fastifyInstance.close()
})

describe('withFunctions', () => {
// Deliberately using `toBe` here to check for referential equality.
it('returns the same fastify instance', async () => {
expect(returnedFastifyInstance).toBe(fastifyInstance)
})
Tobbe marked this conversation as resolved.
Show resolved Hide resolved

it('configures the `@fastify/url-data` and `fastify-raw-body` plugins', async () => {
describe('redwoodFastifyAPI', () => {
it.only('configures the `@fastify/url-data` and `fastify-raw-body` plugins', async () => {
jtoar marked this conversation as resolved.
Show resolved Hide resolved
const plugins = fastifyInstance.printPlugins()

expect(plugins.includes('@fastify/url-data')).toEqual(true)
expect(plugins.includes('fastify-raw-body')).toEqual(true)
})

it('configures two additional content type parsers, `application/x-www-form-urlencoded` and `multipart/form-data`', async () => {
expect(
fastifyInstance.hasContentTypeParser('application/x-www-form-urlencoded')
).toEqual(true)
expect(fastifyInstance.hasContentTypeParser('multipart/form-data')).toEqual(
true
)
})
Tobbe marked this conversation as resolved.
Show resolved Hide resolved

it('can be configured by the user', async () => {
const res = await fastifyInstance.inject({
method: 'GET',
Expand Down
Loading
Loading