Skip to content
This repository has been archived by the owner on Oct 1, 2024. It is now read-only.

Use SewingKitKoa Middleware in createRender #1160

Merged
merged 1 commit into from
Oct 30, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions packages/react-server/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]

- `createRender` now includes automatic sewing-kit-koa set-up. The `createRender` middleware now accepts an `assetPrefix` that is passed to `sewingKitKoa`'s middleware. [[1160](https://github.com/Shopify/quilt/pull/1160)]

## [0.7.3] - 2019-09-30

- Added missing `@shopify/react-cookie` dependency
Expand Down
39 changes: 34 additions & 5 deletions packages/react-server/src/render/render.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import {join} from 'path';
import {existsSync} from 'fs';
import React from 'react';
import {Context} from 'koa';
import compose from 'koa-compose';
import {
Html,
HtmlManager,
Expand All @@ -20,7 +23,10 @@ import {
AssetTiming,
} from '@shopify/react-async';
import {Header, StatusCode} from '@shopify/react-network';
import {getAssets} from '@shopify/sewing-kit-koa';
import {
getAssets,
middleware as sewingKitMiddleware,
} from '@shopify/sewing-kit-koa';
import {getLogger} from '../logger';

export {Context};
Expand All @@ -31,14 +37,20 @@ export interface RenderFunction {
type Options = Pick<
NonNullable<ArgumentAtIndex<typeof extract, 1>>,
'afterEachPass' | 'betweenEachPass'
>;
> & {
assetPrefix?: string;
};

/**
* Creates a Koa middleware for rendering an `@shopify/react-html` based React application defined by `options.render`.
* Creates a Koa middleware for rendering an `@shopify/react-html` based React application defined by `render`.
* @param render
* @param options
*/
export function createRender(render: RenderFunction, options: Options = {}) {
return async function renderFunction(ctx: Context) {
const manifestPath = getManifestPath(process.cwd());
const {assetPrefix} = options;

async function renderFunction(ctx: Context) {
const logger = getLogger(ctx) || console;
const assets = getAssets(ctx);

Expand Down Expand Up @@ -117,5 +129,22 @@ export function createRender(render: RenderFunction, options: Options = {}) {
ctx.throw(StatusCode.InternalServerError, error);
}
}
};
}

return compose([
sewingKitMiddleware({assetPrefix, manifestPath}),
renderFunction,
]);
}

function getManifestPath(root: string) {
const gemFileExists = existsSync(join(root, 'Gemfile'));
if (!gemFileExists) {
return;
}

// eslint-disable-next-line no-process-env
return process.env.NODE_ENV === 'development'
? `tmp/sewing-kit/sewing-kit-manifest.json`
: `public/bundles/sewing-kit-manifest.json`;
}
29 changes: 23 additions & 6 deletions packages/react-server/src/render/test/render.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import React from 'react';
import {Effect} from '@shopify/react-effect/server';
import {middleware as sewingKitKoaMiddleware} from '@shopify/sewing-kit-koa';
import {createMockContext} from '@shopify/jest-koa-mocks';
import withEnv from '@shopify/with-env';
import {createRender} from '../render';
import {mockMiddleware} from '../../test/utilities';

jest.mock('@shopify/sewing-kit-koa', () => ({
middleware: jest.fn(() => mockMiddleware),
getAssets() {
return {
styles: () => Promise.resolve([]),
Expand All @@ -19,7 +22,7 @@ describe('createRender', () => {
const ctx = createMockContext();

const renderFunction = createRender(() => <>{myCoolApp}</>);
await renderFunction(ctx);
await renderFunction(ctx, noop);

expect(await readStream(ctx.body)).toContain(myCoolApp);
});
Expand All @@ -29,11 +32,23 @@ describe('createRender', () => {
const ctx = createMockContext({headers: {'some-header': headerValue}});

const renderFunction = createRender(ctx => <>{ctx.get('some-header')}</>);
await renderFunction(ctx);
await renderFunction(ctx, noop);

expect(await readStream(ctx.body)).toContain(headerValue);
});

it('calls the sewing-kit-koa middleware with the passed in assetPrefix', async () => {
const assetPrefix = 'path/to/assets';
const ctx = createMockContext();

const renderFunction = createRender(() => <></>, {assetPrefix});
await renderFunction(ctx, noop);

expect(sewingKitKoaMiddleware).toHaveBeenCalledWith(
expect.objectContaining({assetPrefix}),
);
});

describe('error handling', () => {
const error = new Error(
'Look, it broken. This is some meaningful error messsage.',
Expand All @@ -47,7 +62,7 @@ describe('createRender', () => {
const ctx = {...createMockContext(), locale: ''};

const renderFunction = createRender(() => <BrokenApp />);
await renderFunction(ctx);
await renderFunction(ctx, noop);

expect(await readStream(ctx.body)).toContain(error.message);
expect(await readStream(ctx.body)).toContain(error.stack);
Expand All @@ -62,7 +77,7 @@ describe('createRender', () => {
.mockImplementation(() => null);

const renderFunction = createRender(() => <BrokenApp />);
await renderFunction(ctx);
await renderFunction(ctx, noop);

expect(throwSpy).toHaveBeenCalledWith(500, new Error(error.message));
});
Expand All @@ -75,7 +90,7 @@ describe('createRender', () => {
const afterEachPass = jest.fn();
const renderFunction = createRender(() => <>Markup</>, {afterEachPass});

await renderFunction(ctx);
await renderFunction(ctx, noop);

expect(afterEachPass).toHaveBeenCalledTimes(1);
});
Expand All @@ -96,7 +111,7 @@ describe('createRender', () => {
},
);

await renderFunction(ctx);
await renderFunction(ctx, noop);

expect(betweenEachPass.mock.calls.length).toBeGreaterThanOrEqual(1);
});
Expand All @@ -111,3 +126,5 @@ function readStream(stream: NodeJS.ReadableStream) {
stream.on('end', () => resolve(response));
});
}

async function noop() {}
19 changes: 1 addition & 18 deletions packages/react-server/src/server/server.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import 'isomorphic-fetch';
import {Server} from 'http';
import {join} from 'path';
import {existsSync} from 'fs';
import Koa, {Context} from 'koa';
import compose from 'koa-compose';
import mount from 'koa-mount';
import {middleware as sewingKitMiddleware} from '@shopify/sewing-kit-koa';
import {createRender, RenderFunction} from '../render';
import {requestLogger} from '../logger';
import {metricsMiddleware as metrics} from '../metrics';
Expand All @@ -29,33 +26,19 @@ interface Options {
export function createServer(options: Options): Server {
const {port, assetPrefix, render, serverMiddleware, ip} = options;
const app = new Koa();
const manifestPath = getManifestPath(process.cwd());

app.use(mount('/services/ping', ping));

app.use(requestLogger);
app.use(metrics);
app.use(sewingKitMiddleware({assetPrefix, manifestPath}));

if (serverMiddleware) {
app.use(compose(serverMiddleware));
}

app.use(createRender(render));
app.use(createRender(render, {assetPrefix}));

return app.listen(port || 3000, () => {
logger.log(`started react-server on ${ip}:${port}`);
});
}

function getManifestPath(root: string) {
const gemFileExists = existsSync(join(root, 'Gemfile'));
if (!gemFileExists) {
return;
}

// eslint-disable-next-line no-process-env
return process.env.NODE_ENV === 'development'
? `tmp/sewing-kit/sewing-kit-manifest.json`
: `public/bundles/sewing-kit-manifest.json`;
}