loading...

My first lambda function with dev.to API

alligatore3 profile image Mattia Zanella Updated on ãƒŧ2 min read

I'm gonna start this article by mentioning this great article by

danivijay image

So this example will be more or less the same but, instead return a simple Yey! string, we will fetch DEV's API to get my personal data.

DEV's endpoints are listed here.
I'm gonna call my file as DEV_profile.js and inside I'll put this:

const https = require("https");

const options = {
  hostname: 'dev.to',
  path: '/api/users/me',
  headers: { 'api-key': 'YOUR_AMAZING_TOKEN' }
}

const getProfile = (event, context, callback) => {
  // Just a guard to prevent other verbs
  if (event.httpMethod !== 'GET') return

  const req = https.request(options, res => {
    let content = ''
    res.setEncoding("utf8");

    res.on('data', data => (content += data));

    res.on('end',
      body => callback(null, { statusCode: 200, body: content })
    );
  })

  req.on('error', error => console.error(error))
  req.end();
};

module.exports = { handler: getProfile }

Disclaimer: I'm not a backend developer so I'm not sure what I'm doing ðŸĪŠ but to handle CORS issues I'm gonna adding some lines to end of the file:

const middy = require('@middy/core')
const cors = require('@middy/http-cors')

/**
 * Let's "middyfy" our handler, then we will be able to attach middlewares to it
 * and Adds CORS headers to responses
 */
const handler = middy(getProfile).use(cors())

module.exports = { handler }

Following this article helped me a lot during development.

Finally you can watch the result here.

That's all 👋 👋

Posted on by:

alligatore3 profile

Mattia Zanella

@alligatore3

Trying to deal with @vuejs at L.I.F.E. ITALIA S.R.L.

Discussion

markdown guide