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

Commit

Permalink
fix: pass in root directory name where image file can be found (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
ericapisani committed Dec 13, 2022
1 parent 2de8830 commit 552ab35
Show file tree
Hide file tree
Showing 14 changed files with 4,198 additions and 3,429 deletions.
74 changes: 74 additions & 0 deletions .github/workflows/cypress-demo.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
name: Run e2e (default demo)
on:
pull_request:
types: [opened, labeled, unlabeled, synchronize]
push:
branches:
- main
paths:
- 'demos/default/**/*.{ts,tsx}'
- 'cypress/e2e/**/*.{ts}'
- 'plugin/src/**/*.{ts}'
jobs:
cypress:
name: Cypress
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Can increase the containers as we add more tests
containers: [1]
steps:
- name: Checkout
uses: actions/checkout@v2

- name: Generate Github token
uses: navikt/github-app-token-generator@v1
id: get-token
with:
private-key: ${{ secrets.TOKENS_PRIVATE_KEY }}
app-id: ${{ secrets.TOKENS_APP_ID }}

- name: Checkout @netlify/wait-for-deploy-action
uses: actions/checkout@v2
with:
repository: netlify/wait-for-deploy-action
token: ${{ steps.get-token.outputs.token }}
path: ./.github/actions/wait-for-netlify-deploy

- name: Wait for Netlify Deploy
id: deploy
uses: ./.github/actions/wait-for-netlify-deploy
with:
site-name: gatsby-runner-hp
timeout: 300

- name: Deploy successful
if: ${{ steps.deploy.outputs.origin-url }}
run: echo ${{ steps.deploy.outputs.origin-url }}

- name: Node
uses: actions/setup-node@v2
with:
node-version: '16'

- run: yarn

- name: Cypress run
if: ${{ steps.deploy.outputs.origin-url }}
id: cypress
uses: cypress-io/github-action@v2
with:
browser: chrome
headless: true
record: true
parallel: true
config-file: cypress/config/ci.config.ts
group: 'Gatsby Runner - Demo'
spec: cypress/e2e/*
env:
DEBUG: '@cypress/github-action'
CYPRESS_baseUrl: ${{ steps.deploy.outputs.origin-url }}
CYPRESS_NETLIFY_CONTEXT: ${{ steps.deploy.outputs.context }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CYPRESS_RECORD_KEY: ${{ secrets.DEFAULT_CYPRESS_RECORD_KEY }}
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,17 @@ You must then change your build command from `gatsby build` to `gatsby-runner`.
The `gatsby-runner` script wraps the `gatsby cli`, and registers as a handler for Gatsby's jobs API. It listens for image processing jobs and then, rather than processing the image, it writes the job as a JSON file to the cache. It then generates a Netlify Function called `gatsby-image`, which includes all of the code required to process the image at runtime, as well as the JSON files containing the details of the image processing job.

When a request is made for an image, it instead calls the `gatsby-image` function, which looks up the job for that image in the cache, loads the original image, and then processes and returns it. While this is slow for the first request, as the function is an [On-Demand Builder](https://docs.netlify.com/configure-builds/on-demand-builders/) that image is then cached at the edge for subsequent requests so is very fast.

## Running Cypress tests locally

In order to test the use of the plugin on the demo site within this repository, do the following first to get the demo site running (requires the [netlify-cli](https://cli.netlify.com/getting-started) to be installed):

```
cd demos/default
netlify build
netlify dev --framework=#static
```

This will build the demo site and then start a static HTTP server serving files from the publish directory rather than through the Gatsby server that starts with `gatsby develop` in order to test the behaviour introduced in the plugin such as redirects that are introduced [here](https://github.com/netlify/gatsby-runner/blob/bc0a740f34aae31c878518f2765e42ed5baeaba8/plugin/src/index.ts#L47-L51).

Once that's running, in a separate shell, run `yarn cy:open`
8 changes: 8 additions & 0 deletions cypress/config/ci.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from "cypress";

export default defineConfig({
e2e: {
// The baseUrl is set within `.github/workflows/cypress-demo.yml`
projectId: "vq2rbp",
},
});
7 changes: 7 additions & 0 deletions cypress/config/local.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "cypress";

export default defineConfig({
e2e: {
baseUrl: "http://localhost:8888"
},
});
7 changes: 7 additions & 0 deletions cypress/e2e/default.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
describe('Home page', () => {
it('successfully renders the Gatsby logo', () => {
cy.visit('/')
cy.get('[alt="Gatsby logo"]')
.should('be.visible')
})
})
5 changes: 5 additions & 0 deletions cypress/fixtures/example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}
39 changes: 39 additions & 0 deletions cypress/support/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/// <reference types="cypress" />
// ***********************************************
// This example commands.ts shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
//
// declare global {
// namespace Cypress {
// interface Chainable {
// login(email: string, password: string): Chainable<void>
// drag(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
// dismiss(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
// visit(originalFn: CommandOriginalFn, url: string, options: Partial<VisitOptions>): Chainable<Element>
// }
// }
// }
// eslint-disable-next-line import/no-unassigned-import
import '@testing-library/cypress/add-commands';
20 changes: 20 additions & 0 deletions cypress/support/e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// ***********************************************************
// This example support/e2e.ts is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')
11 changes: 11 additions & 0 deletions cypress/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"types": ["cypress", "@testing-library/cypress"]
},
"include": [
"../node_modules/cypress",
"./**/*.ts"
]
}
2 changes: 1 addition & 1 deletion demos/default/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const IndexPage = () => {
🎉🎉🎉
</h1>

<StaticImage src="../images/icon.png" alt="Gatsby" />
<StaticImage src="../images/icon.png" alt="Gatsby logo" />
</main>
);
};
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
"name": "gatsby-runner",
"version": "1.0.0",
"description": "This is an experimental build runner for Gatsby on Netlify, which can dramatically improve build times for sites with lots of images.",
"devDependencies": {},
"devDependencies": {
"@testing-library/cypress": "^8.0.7",
"cypress": "^12.0.2"
},
"scripts": {
"cy:open": "cypress open --config-file cypress/config/local.config.ts",
"release": "yarn workspace @netlify/gatsby-runner release"
},
"repository": {
Expand Down
12 changes: 5 additions & 7 deletions plugin/src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ const downloadFile = async (
downloadingFiles.delete(url)
reject(
new Error(
`Failed to download ${url}: ${response.statusCode} ${
response.statusMessage || ''
`Failed to download ${url}: ${response.statusCode} ${response.statusMessage || ''
}`
)
)
Expand All @@ -55,12 +54,13 @@ const downloadFile = async (
// 6MB is hard max Lambda response size
const MAX_RESPONSE_SIZE = 6291456

async function imageHandler(event: HandlerEvent) {
export const getImageHandler = (rootDirName: string) => builder(async function imageHandler(event: HandlerEvent) {
const url = new URL(event.rawUrl)
console.log(`[${event.httpMethod}] ${url.pathname}`)
const [, , fileHash, queryHash] = url.pathname.split('/')
let imageData
const dataFile = resolve(__dirname, `jobs/${fileHash}/${queryHash}.json`)
const dataFile = resolve(rootDirName, `jobs/${fileHash}/${queryHash}.json`)

if (!existsSync(dataFile)) {
console.log(`Data file ${dataFile} does not exist`)
return {
Expand Down Expand Up @@ -138,6 +138,4 @@ async function imageHandler(event: HandlerEvent) {
body: readFileSync(outputPath, 'base64'),
isBase64Encoded: true,
}
}

export const handler = builder(imageHandler)
})
8 changes: 6 additions & 2 deletions plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,12 @@ export const onBuild: OnBuild = async ({ constants, netlifyConfig, utils }) => {
await ensureDir(functionDir)
await emptyDir(functionDir)
await writeFile(
path.join(functionDir, 'gatsby-image.ts'),
`export { handler } from '@netlify/gatsby-runner/handler'`
path.join(functionDir, 'gatsby-image.js'),
`
const {getImageHandler} = require('@netlify/gatsby-runner/handler')
module.exports.handler = getImageHandler(__dirname)
`
)
await copy(cacheDir, path.join(functionDir, 'jobs'))
netlifyConfig.functions['gatsby-image'] = {
Expand Down
Loading

0 comments on commit 552ab35

Please sign in to comment.