Skip to content

Instantly share code, notes, and snippets.

@rastandy
Forked from lilactown/cljs-serverless.md
Created July 11, 2018 22:25
Show Gist options
  • Save rastandy/f3004f969842e51411a228421ff2e58d to your computer and use it in GitHub Desktop.
Save rastandy/f3004f969842e51411a228421ff2e58d to your computer and use it in GitHub Desktop.
CLJS in AWS Lambda Quick Start

CLJS in AWS Lambda Quick Start

Setup

First, a few dependencies:

  1. Leiningen: https://leiningen.org/
  2. Node.js & NPM: https://nodejs.org/
  3. Serverless: https://serverless.com/
  4. An active AWS account: https://aws.amazon.com/

Second, take the time to go through the guides on the Serverless website for configuring AWS Lambda and the serverless CLI. It would probably be a good idea to create a simple project and deploying it before going through this guide.

Create our application

lein new figwheel-node cljs-lambda-fn

cd cljs-lambda-fn

npm i

serverless create --template aws-nodejs

core.cljs:

(ns cljs-lambda-fn.core
  (:require [cljs.nodejs :as nodejs]))

(nodejs/enable-util-print!)

;; (defn -main []
;;   (println "Hello world!"))

;; (set! *main-cli-fn* -main)

(defn greet [event ctx cb]
  ;; see `handler.js` generated by serverless
  ;; for reference to `cb` signature
  (cb nil (clj->js
       {:statusCode 200
        :headers {"Content-Type" "text/html"}
        :body "<h1>Hello, world!</h1>"})))

(set! (.-exports js/module) #js
      {:greet greet})

Build: lein cljsbuild once

Test in a Node.js REPL:

$ node
> require('./server.js').greet(null, null, (_, v) => console.log(v))
{ statusCode: 200,
  headers: { 'Content-Type': 'text/html' },
  body: '<h1>Hello, world!</h1>' }
undefined

Configuring Serverless

In serverless.yml, edit these fields:

service: cljs-lambda-greet # something unique
...

functions:
  hello:
    handler: server.greet
    events:
      - http:
          path: greet
          method: get

Deploying

$ serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Creating Stack...
Serverless: Checking Stack create progress...
.....
Serverless: Stack create finished...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (2.15 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..............................
Serverless: Stack update finished...
Service Information
service: cljs-lambda-greet
stage: dev
region: us-east-1
stack: cljs-lambda-greet-dev
api keys:
  None
endpoints:
  GET - https://mw0r86y2s3.execute-api.us-east-1.amazonaws.com/dev/greet
functions:
  hello: cljs-lambda-greet-dev-hello

$ curl https://mw0r86y2s3.execute-api.us-east-1.amazonaws.com/dev/greet
<h1>Hello, world!</h1>%

Success!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment