-
Notifications
You must be signed in to change notification settings - Fork 8
Format to snippets for just boilerplate #5
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
base: master
Are you sure you want to change the base?
Changes from all commits
24b9693
1898a11
cf85ebe
53e94f6
cf49eb4
ffbf2f2
77ea447
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,6 @@ | ||
| node_modules/* | ||
| node_modules/* | ||
| worker/* | ||
| *.lock | ||
| wrangler.toml | ||
| .vscode* | ||
| receiveserver.js |
| 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, | ||
| "printWidth": 80 | ||
| } | ||
This file was deleted.
| 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 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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. | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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:
|
||
|
|
||
| ``` | ||
| 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. | ||
| 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) | ||
| }) |
This file was deleted.
| 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) | ||
| } |
| 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) | ||
| } |
| 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() | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
People typically use
"tabWidth": 2in the JS community (in my experience). This is also the default value for this option, so it might be better to omit this.There was a problem hiding this comment.
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: allbecause it eliminates the time spent and annoying compilation errors that arise from missing commas.