Giter Club home page Giter Club logo

cloudflare-2020-general-engineering-assignment's Introduction

General Assignment

What is it?

In this exercise, you'll deploy a Cloudflare Workers project in order to build a linktree-style website. Below is a list of requirements and success criteria for your finished project.

Requirements

Deploy a JSON API

Create a new Workers project using Wrangler. This project will respond to two kinds of requests, one to generate a JSON API (defined below), and second, to serve an HTML page (see "Set up an HTML page")

To begin, you should define an array of links. The links should be a JavaScript array, with a number of link objects, each with a name and URL string. See the below example for one of these link objects:

{ "name": "Link Name", "url": "https://linkurl" }

You should define at least three link objects inside of your array.

Once you've defined this array, set up a request handler to respond to the path /links, and return the array itself as the root of your JSON response.

In addition, you should ensure that the API response has the correct Content-Type header to indicate to clients that it is a JSON response.

You should be able to test that this works as expect by running wrangler dev to access your Workers application locally. Visit localhost:8000/links to confirm that your application returns the link array as a JSON response.

Set up an HTML page

With your API deployed, you can flesh out the rest of your application. If the path requested is not /links, your application should render a static HTML page, by doing the following steps:

  1. Retrieve a static HTML page
  2. Get the links from your previously deployed JSON response
  3. Use HTMLRewriter to add these links to the static HTML page
  4. Return the transformed HTML page from the Worker

Retrieve a static HTML page

Your Worker should begin by making a fetch request to https://static-links-page.signalnerve.workers.dev.

The response from this URL will be a static HTML page that you can enhance using HTMLRewriter.

Note that you need to make the request to this HTML page in your Worker. The URL will return multiple static HTML pages randomly, so you should not copy-paste the HTML into your Worker, as you will not complete the exercise correctly.

Use HTMLRewriter to update the page

Using HTMLRewriter, you should transform the static HTML response from $URL, and pass in the links array you previously defined into the page. Note that this means that your links array should be available as a variable for both your previous /links endpoint, as well as this static HTML section. Target the div#links selector, and add in a new a for each link in your API using HTMLRewriter.

In order to use the links inside of your HTMLRewriter handler, you can use a custom class to pass in arguments, for instance:

class LinksTransformer {
  constructor(links) {
    this.links = links
  }
  
  async element(element) {
    // Your code
  }
}

Here's what the output of the div#links section should look like:

<div id="links">
  <a href="https://asampleurl.com">A sample URL</a>
  <a href="https://anothersampleurl.com">Another sample URL</a>
  <a href="https://afinalsampleurl.com">A final sample URL</a>
</div>

You should also remove the display: none from the div#profile container, and inside of it, update the two child elements to show your user avatar and name.

To do this, target img#avatar and set the src attribute to a profile image.

Do the same for h1#name, setting the text to your username.

Return the transformed HTML page from the Worker

Once you've passed the static HTML response through your HTMLRewriter instance, you can return it as the response from the Worker.

Ensure that the correct Content-type header is set for this page, allowing it to render as HTML in a browser.

Once you've completed the code for this project, you can deploy it using wrangler publish. Follow our Quick Start guide to learn how to deploy Workers applications. You should submit both the JSON API URL and your deployed webpage for grading.

Add a link to your deployed worker to your repo

Create a URL.txt that contains one line in it with the URL of your page. For example if my assignment was deployed at https://myassignment.mydomain.com/ I would put the following in URL.txt:

https://myassignment.mydomain.com/

We will test your code by visiting the URL in that file and the /links endpoint as well. In the above example we would test https://myassignment.mydomain.com/ and https://myassignment.mydomain.com/links .

Extra Credit

  1. Provide social links

Remove the display: none style from div#social, and add any number of social links as children to the container. The children of this container should be a links, with svg icons as the children of those links. For example SVGs, use https://simpleicons.org.

<div id="links">
  <a href="someurl.com">
    <svg></svg>
  </a>
</div>
  1. Update the title field

Using the HTMLRewriter, target the title tag and update the text inside to your name.

  1. Change the background color:

Using HTMLRewriter, target the body element and change the background color. You can simply swap out the bg-gray-900 class with another class from Tailwind CSS's color palette, or set a background-color style to a color, gradient, or image of your choice.

  1. Do the Systems Assignment that depends on the work you've done here.

cloudflare-2020-general-engineering-assignment's People

Contributors

cloudflare-hiring avatar jmadruga-cf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cloudflare-2020-general-engineering-assignment's Issues

Image src is not working, htmlRewriter

I am trying to add an src attribute to the img element by element.setAttribute("src", "./image.jpg") in index.js, where image.jpg is at the same level as index.js. However, when I render it by wrangler dev, the image is not showing up. I made the get request on Postman and I can find the attributed being successfully added. Moreover, if I take HTML source and open it as a static HTML, the image is showing.

ReferenceError: addEventListener is not defined

Hello. I am not able to use console.log() to print anything because of this error after I "run" the code in Visual Studio Code to see why.
I get this in the terminal after I run it.

ReferenceError: addEventListener is not defined
    at Object.<anonymous> (/home/username/Desktop/my-worker/index.js:5:1)
    at Module._compile (internal/modules/cjs/loader.js:1076:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

I have this code. No syntax errors at all. I do not think it's in my code. I might need to do something with the file called internal/modules/cjs/loader.js.

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event))
})

Any ideas on how I can fix it? I have already deployed it with wrangler publish, again I can't see anything print in the console in chrome devs.

I'm on Linux if that matters.

Thanks.

How to add tags inside a div

In my code I successfully retrieve the div#links element but don’t know how I can add the a tags inside the div.

Error in wrangler

I installed wrangler but when I try to do anything with it, I get the error:

.nvm/versions/node/v13.13.0/lib/node_modules/@cloudflare/wrangler/node_modules/binary-install/src/binary.js:60
      throw `You have not installed ${this.name ? this.name : "this package"}`;
      ^
You have not installed wrangler
(Use `node --trace-uncaught ...` to show where the exception was thrown)

How do I fix this? I can't proceed with the assignment until I get wrangler working.

You have not installed wrangler

I keep recieving this error that I didnt install wrangler. I've tried all solutions from here and here, but none of them work. Help would be appreciated!

$ sudo npm install @cloudflare/wrangler -g --unsafe-perm=true --allow-root
/usr/local/bin/wrangler -> /usr/local/lib/node_modules/@cloudflare/wrangler/run-wrangler.js

> @cloudflare/[email protected] postinstall /usr/local/lib/node_modules/@cloudflare/wrangler
> node ./install-wrangler.js

Downloading release https://workers.cloudflare.com/get-npm-wrangler-binary/1.11.0/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/[email protected]
added 34 packages from 21 contributors in 4.462s
$ wrangler --help

/usr/local/lib/node_modules/@cloudflare/wrangler/node_modules/binary-install/src/binary.js:60
      throw `You have not installed ${this.name ? this.name : "this package"}`;
      ^
You have not installed wrangler
(Use `node --trace-uncaught ...` to show where the exception was thrown)
$ 

Worker script fetching from /links giving timeout

I am done with all the setup (HTML and API) but stuck with a small issue. I have /links and the HTML page in the same worker script. After writing logic for /links I published the worker on my dev setup. Now for HTML if I try to fetch from /links from my published project I am getting timeout error.

But if I preview the same page from the Cloudflare dashboard under "Quick Edit" option for my worker I am able to see the page since the fetch works that time.

Not sure what to do with this?

Connection Timeout 522

I am getting 522 connection timeout after wrangler publish. Should I wait before trying again?
Another interesting observation, deleted workers are still responding to requests.

TypeError in worker.js

I keep encountering an issue when I try to run my code:

Uncaught (in promise)
TypeError: e.handler is not a function
    at t.exports.route (worker.js:1:2632)
    at worker.js:1:1610
Uncaught (in response)
TypeError: e.handler is not a function

This is not a part of the code I've written and I can't seem to figure out what's going on. I was able to put the links into the HTML (checked using print statements) but it won't let me send it back in a response. I'm not sure if I should be calling some method on the value returned after calling transform on the HTML, since I couldn't find any documentation on how to use HTMLWriter in conjunction with the Router boilerplate.

Json data and extra credit

Are we allowed to add additional fields to our links array for the extra credit?
Or are we only allowed to have the 'name' and 'url' fields?

HTML rewriter transform not going inside of element() { } method

Hello,
I am trying to work with HTML rewriter but having some trouble.
Here is the code i am trying to run

class LinksTransformer {
    constructor() {
      this.links = linksData
      console.log('constructorrr')
    }
    element(element) {
      console.log('comeon come here')
      console.log(`Incoming element: ${element.tagName}`)
    }
    text() {
      console.log('hereeee')
    }
  }
async function transformResult(response) {
    return new HTMLRewriter()
      .on("*", new LinksTransformer())
      .transform(response)
}

Although, when the transformResult function is called, and hence HTMLRewriter, which will create new instance of LinksTransformer() function.
I am getting console.log from the constructor. Although, I am not getting any log from element() or text() functions.

I was wondering if there is some issue with the HTML rewriter.
I examined the response and response.text() contains the HTML that i want to edit.

I looked up in the docs and community questions but nothing helped. Any help is appreciated! Thanks!!

HTMLRewriter Usage

I am currently on the step where I make the request to the provided URL to get the HTML page and need to use the HTMLRewriter class. I understand that I use this class to change the inner link elements with the ones in my array but I am slightly confused on the syntax. I have a handleEvent function that makes the request to the URL but I am unsure how to target the specific div element using the HTMLRewriter class. For instance if I use the element.getAttribute() function how would I pass in the literal "links" id element? I tried just "links" but it didn't work. Any suggestions or examples?

Editing Style property through HTMLRewriter

So I am able to remove the style property altogether but there are no selectors for a particular style property.
Usecase: if the style property had other values like <h1 style="color:blue;text-align:center;display:none">This is a header</h1> , The HTMLRewriter does not have support to remove just the display:none CSS style property.

Should I assume that if there's display:none is present then there will not be any other style properties?

Edit:
Clarity on my question: Since there is no selector for particular CSS property from HTMLRewriter, is it okay to just remove the style property altogether?

Issues in HTMLRewriter

I am trying to use Example in my implementation. When i try to used two .on statements it returns with error stack that is not traceable IMO. It returns errors for worker.js which is a single line transformed js that wrangler constructs at runtime.

piece of code change that breaks the implementation:

const rewriter = new HTMLRewriter()
  .on('div', new AttributeRewriter('style'))
  .on('img', new AttributeRewriter('src'))

Error stack:

 MINGW64 ~/my-worker/my-worker-with-router_or (master)
$ wrangler dev
 Built successfully, built project size is 1 KiB.
 Listening on http://127.0.0.1:8787
 Detected changes...
Uncaught
ReferenceError: Cannot access 'a' before initialization
    at Object.<anonymous> (worker.js:1:1506)
    at n (worker.js:1:110)
    at worker.js:1:902
    at worker.js:1:911
Uncaught (in promise)
ReferenceError: Cannot access 's' before initialization
    at worker.js:1:1117
    at async worker.js:1:1019
Uncaught (in response)
ReferenceError: Cannot access 's' before initialization

Unable to submit on Greenhouse

Hi, I've been trying to attach my work to the Greenhouse link for the past week but I get the following error whenever I try to attach my zip files:
cf-assignment-worker.zip failed to upload: Could not contact request signing server. Status = 500

I've tried contacting the recruiting team but I haven't gotten a response, so I thought to try here. Thank you for your help!

Extra Credit discrepancy

For the extra credit 1. we are asked to change the contents of div#social but the example image shows div#link. Kindly clear this discrepancy.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.