Let’s Make Serverless Endpoints

Jun 24, 2018 · 340 words · 2 minute read lambda wireframe

To get our function going, we need to log on to https://webtask.io and make an empty function. Webtask has some pre-built templates, but for this one, let’s start with a blank slate and take this step by step.

webtask

Next, we need to hit that wrench icon and go to the NPM modules section. This is where we are going to install some modules for our function. For our example, we are going to use the following packages

•   postcss
•   postcss-css-variables
•   postcss-for
•   postcss-clean

Now that we have our packages installed, let’s setup our file. First, let’s include our NPM modules.

const postcss = require('postcss');
const cssvariables = require('postcss-css-variables');
const pFor = require('postcss-for');
const clean = require('postcss-clean');

Then we are going set up module.exports. You can read more about the context object that is available in Webtask here.

module.exports = function(context, cb) {
}

Next, let’s set the CSS we are going to process. This line is going to be in our HTML later.

const mycss = context.body.pCSS;

Then we are going to process our CSS without NPM modules. We are going to setup up postcss and then pass our extensions through that as well. Then we’ll send output through our callback function.

  var output = postcss([
		cssvariables(),
		pFor(),
		clean()
	])
	.process(mycss)
	.css;
	
  cb(null, {output});

Let’s move to the front end and build a simple form to post CSS to. On the bottom of the Webtask edit screen, you can see

See the Pen post-css by John Siwicki (@siwicki) on CodePen.

You can see it the above code pen that is sending data to my endpoint, and you can try it out.

If you want to try some CSS, here is a block that you can use.

:root {
	--width: 100px;
}

@media (max-width: 1000px) {
	:root {
		--width: 200px;
	}
}

.box {
	width: var(--width);
}

Server-less or function as a service is going to be a powerful movement for front-end people who want to add a little extra functionality that can be offloaded into these separate functions.