Skip to content
Open
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
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
node_modules/*
node_modules/*
worker/*
*.lock
wrangler.toml
.vscode*
receiveserver.js
11 changes: 6 additions & 5 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
trailingComma: 'es5',
tabWidth: 4,
semi: false,
singleQuote: true,
};
"singleQuote": true,
"semi": false,
"trailingComma": "es5",
"tabWidth": 4,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

People typically use "tabWidth": 2 in the JS community (in my experience). This is also the default value for this option, so it might be better to omit this.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd also enforce trailingComma: all because it eliminates the time spent and annoying compilation errors that arise from missing commas.

"printWidth": 80
}
7 changes: 0 additions & 7 deletions .prettierrc.js

This file was deleted.

12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
## fetch

Examples of making fetch requests from within your Worker script including generating JSON post requests then reading in the resulting response body, aggregating multiple requests into one response, and following/catching redirects.
Examples of making fetch requests from within your Worker script including:

[`index.js`](https://github.com/cloudflare/worker-template-fetch/blob/master/index.js) is the content of the Workers script.
- Generating JSON post requests then reading in the resulting response body
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"post" should probably be capitalized here (as GET is below). Maybe rewrite as:

Generating POST requests then reading in the resulting response body as JSON

- Generating GET requests then reading in the resulting response body as HTML
- Aggregating multiple requests into one response

[`index.js`](https://github.com/cloudflare/worker-template-fetch/blob/master/index.js) is the content of the Workers script. The `snippets` folders holds the logic for individual endpoints' functionality.

Live Demos are hosted on `workers-tooling.cf/demos/fetch`:
[Demo JSON](http://workers-tooling.cf/demos/fetch/json) | [Demo HTML](http://workers-tooling.cf/demos/fetch/html)

#### Wrangler
To generate using [wrangler](https://github.com/cloudflare/wrangler)

To generate using [wrangler](https://github.com/cloudflare/wrangler) on a brand new project with all the included snippets.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grammar here is a lil weird. What do you think about changing to:

You can use wrangler to generate a new project including these snippets with the following command:


```
wrangler generate myApp https://github.com/cloudflare/worker-template-fetch
```

#### Serverless

To deploy using serverless add a [`serverless.yml`](https://serverless.com/framework/docs/providers/cloudflare/) file.
129 changes: 19 additions & 110 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,117 +1,26 @@
/**
* Example someHost is set up to respond with JSON and HTML according to the path
* */
const someHost = 'https://workers-tooling.cf/demos'
const someJSONURL = someHost + '/requests/json'
const someHTMLURL = someHost + '/static/html'
const someJSONToSend = {
results: ['default data to send'],
errors: null,
msg: 'I sent this to the fetch',
}
const someDefaultJSONToRespond = {
results: ['default result'],
errors: null,
msg: 'success in sending a POST',
}
import { handleRequest as postFetch } from './snippets/postJSON'
import { handleRequest as fetchHTML } from './snippets/fetchHTML'
import { handleRequest as aggregateRequests } from './snippets/aggregateRequests'

/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response to
*/
async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get('content-type')
addEventListener('fetch', event => {
const { request } = event
const { url } = request

if (contentType.includes('application/json')) {
const body = await response.json()
return JSON.stringify(body)
} else if (contentType.includes('application/text')) {
const body = await response.text()
return body
} else if (contentType.includes('text/html')) {
const body = await response.text()
return body
} else {
const body = await response.text()
return body
}
}
// Set default response
let response = new Response('Endpoint not found', {
status: 404,
})

/**
* fetchPostJson sends a POST request with data in JSON and
* and reads in the response body. Use await fetchPostJson(..)
* in an async function to get the response body
* @param {string} url the URL to send the request to
* @param {BodyInit} body the JSON data to send in the request
*/
async function fetchPostJson(url, body = {}) {
const init = {
body: JSON.stringify(body),
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}

const response = await fetch(url, init)
const results = await gatherResponse(response)
const retBody = Object.assign(someDefaultJSONToRespond, { results })
return JSON.stringify(retBody)
}

/**
* fetchGetHtml sends a GET request expecting html
* Use await fetchGetHtml(..) in an async function to get the HTML
* @param {string} url the URL to send the request to
*/
async function fetchGetHtml(url) {
const init = {
method: 'Get',
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}

const response = await fetch(url)
const respBody = await gatherResponse(response)
return respBody
}

/**
* Example of how fetch methods above can be used in an application
* */

addEventListener('fetch', async event => {
const { url, method } = event.request

// Set respBody and init according to the route
// and method of the incoming request
if (url.endsWith('/html')) {
init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
if (url.endsWith('/html')) {
response = fetchHTML(request)
}
respBody = fetchGetHtml(someHTMLURL)
}

if (url.endsWith('/json')) {
init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
if (url.endsWith('/json')) {
response = postFetch(request)
}
if (url.endsWith('/aggregateRequests')) {
response = aggregateRequests(request)
}
respBody = fetchPostJson(someJSONURL, someJSONToSend)
}

// Turn the the respBody string into a Response
// return this response to the requester
event.respondWith(
(async function() {
const body = await respBody
return new Response(body, init)
})()
)
// return the assigned response to the requester
return event.respondWith(response)
})
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"name": "{{ project-name }}",
"version": "1.0.0",
"description": "package for creating workers templates",
"main": "index.js",
Expand All @@ -10,9 +9,13 @@
"author": "{{ authors }}",
"license": "ISC",
"devDependencies": {
"husky": "^2.7.0",
"prettier": "^1.17.0"
},
"dependencies": {
"serverless-cloudflare-workers": "^1.2.0"
"husky": {
"hooks": {
"pre-commit": "npm run format",
"pre-push": "npm run format"
}
}
}
71 changes: 0 additions & 71 deletions receive-server.js

This file was deleted.

33 changes: 33 additions & 0 deletions snippets/aggregateRequests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import gatherResponse from './lib/gatherResponse'

/**
* Example someHost is set up to return JSON responses
* Replace url1 and url2 with the hosts you wish to
* send requests to
* @param {string} url the URL to send the request to
*/
const someHost = 'https://workers-tooling.cf/demos'
const url1 = someHost + '/requests/json'
const url2 = someHost + '/requests/json'
const type = 'application/json;charset=UTF-8'

/**
* handleRequest sends a GET request to two urls
* and aggregates the responses into one response
* @param {Request} request the incoming request
*/
export async function handleRequest(request) {
const init = {
headers: {
'content-type': type,
},
}

const responses = await Promise.all([fetch(url1, init), fetch(url2, init)])
const results = await Promise.all([
gatherResponse(responses[0]),
gatherResponse(responses[1]),
])

return new Response(results, init)
}
26 changes: 26 additions & 0 deletions snippets/fetchHTML.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import gatherResponse from './lib/gatherResponse'

/**
* Example someHost at url is set up to respond with HTML
* Replace url with the host you wish to send requests to
* */
const someHost = 'https://workers-tooling.cf/demos'
const url = someHost + '/static/html'

/**
* handleRequest sends a GET request expecting html
* and then returns a response with that HTML
* @param {Request} request the incoming request
*/
export async function handleRequest(request) {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}

const response = await fetch(url, init)
const results = await gatherResponse(response)

return new Response(results, init)
}
19 changes: 19 additions & 0 deletions snippets/lib/gatherResponse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
export default async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get('content-type')

if (contentType.includes('application/json')) {
return await response.json()
} else if (contentType.includes('application/text')) {
return await response.text()
} else if (contentType.includes('text/html')) {
return await response.text()
} else {
return await response.text()
}
}
Loading