LoginSignup
18
18

More than 5 years have passed since last update.

AWS Lambda を CoffeeScript で書いてみた

Last updated at Posted at 2014-12-03

きっかけ

とあるアプリをLambdaで書こうとしたんですが、素のJSだと文字列代入とか非常に面倒臭い。
あといちいち funciton(){}; とか書きたくないでござる...
というわけで、CoffeeScriptで書く事にしました。

HelloWorld for Lambda in CoffeeScript

例えばこれが

console.log('Loading event');

exports.handler = function(event, context) {
    console.log('value1 = ' + event.key1);
    console.log('value2 = ' + event.key2);
    console.log('value3 = ' + event.key3);
    context.done(null, 'Hello World');  // SUCCESS with message
};

こうなって

~/work/lambda$ cat helloworld.coffee
console.log 'Loading event'

exports.handler = (event, context) ->
  console.log "value1 = #{event.key1}"
  console.log "value2 = #{event.key2}"
  console.log "value3 = #{event.key3}"
  context.done null, 'Hello World'  # SUCCESS with message

こうじゃ

~/work/lambda$ coffee -p helloworld.coffee
(function() {
  console.log('Loading event');

  exports.handler = function(event, context) {
    console.log("value1 = " + event.key1);
    console.log("value2 = " + event.key2);
    console.log("value3 = " + event.key3);
    return context.done(null, 'Hello World');
  };

}).call(this);

実際にアプリケーションを書いてみよう

作ったアプリは lambdacast.coffee に置きました。
S3 bucket にメディアファイルを置いたら、自動的にpodcast用のRSSフィードを作成・更新するアプリです。

下記に引用したXML生成の際に、ヒアドキュメントやインラインでの変数展開を使用したかったのが、CoffeeScriptで書いた理由です。

        for item in items when item.Key isnt "rss"
          xml+="""
  <item>
    <title>#{item.Key}</title>
    <link>http://#{bucket}.s3.amazonaws.com/#{item.Key}</link>
    <description>#{item.Size} Bytes</description>
    <enclosure url="http://#{bucket}.s3.amazonaws.com/#{item.Key}" type="audio/mpeg"/>
    <pubDate>#{item.LastModified}</pubDate>
  </item>

"""

デモ

lambda scriptをイベントに設定して、mp3やmp4ファイルを置きます。
そうすると、同じbucketにrssファイルが出来るので、それをiTunesでURLを指定して購読します。
iTunes

bucketにメディアファイルを追加でアップロードしてみます。
s3 upload

自動的にファイルの追加を検知してlambda functionが実行されます。
cw logs

Podcastを更新すると、
iTunes
新しく追加したファイルが配信されました。

非常に簡単にpodcastが作れてしまう事に驚きです。

おわりに

s3を使用したstatic web serverと、JS SDKと、lambdaを組み合わせたら、もっともっと面白いものがお手軽に作れそうですね。

Enjoy!

18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18