Pass variables between different server-less functions

Viewed 35

I am building an application using the Twitter API and Netlify (aws lambda functions) This API requires these steps:

  1. When the user goes to my /auth function, a link to the Twitter authentication is created
  2. Once the user clicks that link, he is redirected to Twitter where a pop-up asks to allow my app to connect.
  3. Once the user approves, he is redirected to my /auth function again but this time the authCode is set to a number rather than being undefined. This authCode is used to instantiate the twitter client class and authorize it.
  4. A new instance of the Twitter client is created and authorized. This instance allows to query the tweets

1, 2 and 3 works. However, the authorized instance only lives inside the /auth function. How can I pass it to different functions without losing its instantiation?

How can I pass this instance to different server-less functions?

client = new Client(OAuthClient) this is what I want to pass around.

I tried with a Middleware with little success. It seems the twitter client class gets re-instantiated (so without authorization) for every server-less function

https://playful-salmiakki-67d50e.netlify.app/.netlify/functions/auth

import Client from 'twitter-api-sdk';


let client: Client;

const auth = async (event, context, callback) => {

  const authCode = event.queryStringParameters ? event.queryStringParameters.code : undefined;

  const authUrl = OAuthClient.generateAuthURL({
    state: 'STATE',
    code_challenge: 'challenge',
  });

  console.log('HERE LINK:');
  console.log(authUrl);

  if (authCode) {
    await OAuthClient.requestAccessToken(authCode as string);
    client = new Client(OAuthClient); <-- THIS IS WHAT I WANT TO PASS TO DIFFERENT FUNCTIONS
  }
  
  return {
    statusCode: 200,
    body: JSON.stringify({ message: 'Auth, go to the url displayed terminal'}),
    myClient: client
  };
};

exports.handler = middy().use(myMiddleware()).handler(auth);
0 Answers
Related