DEV Community

Cover image for My first Serverless service
Amir Maralani
Amir Maralani

Posted on

My first Serverless service

Recently I was going to run a service on Fandogh Paas with a custom domain and ended up using Cloudflare. When setting up stuff something caught my eye: Workers. I knew about the concept of Serverless a little but due to the circumstances using AWS is somewhat out of reach for me, so why not use this instead?!

I tried to create something with it. But the big question was what to build. Last year I created a little Discord bot to retrieve the current AQI of the provided city but since we are not using Discord anymore it's obsolete. Let's do it serverless this time!

The idea of using serverless to just call another API and pass the response on looks a bit redundant, but I guess it's good enough for learning new stuff. So I got an API token from Air Quality Open Data Platform and started coding.

There's a fair amount of documents and examples on the Cloudflare Workers site, and of course, you will need enough JavaScript knowledge.

Here's my code :

const aqiInfoUrl = "https://api.waqi.info/feed/"

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

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  const queryString = request.url.split('?');
  let city = queryString[1].split('=')[1];

  let response = await getAQIFromAPI(city);
  return new Response(response.data.aqi, {status: 200});
}

async function getAQIFromAPI(city) {
  let fullUrl = aqiInfoUrl + city + '/?token='+ API_TOKEN;
  const response = await fetch(fullUrl);
  return await response.json();
}
Enter fullscreen mode Exit fullscreen mode

What it basically does is that when called, tries to find the city from the query string and sends a request to "https://api.waqi.info/feed/" with the provided city and the token which is saved as an environment variable.

It is not the best way it could be written, but I'm very new to this! Please give me your suggestions in the comment section.

PS: I'm thinking about a Telegram bot using the KV store ... Maybe the next post!

Top comments (0)