Reputation: 9159
There is a concern about potential problem with reusable variables in aws-lambda
.
A user's locale is passed as
Browser cookies
=> AWS API Gateway
=> Lambda (NodeJS 6.10)
On the server side localization is implemented with a static variable in a class. Presenting typescript
code for clarity but can be done in pure ECMAScript.
export default class Language
{
public static Current: LanguageCode = LanguageCode.es;
}
Static Language.Current
variable is used across different parts of the application for manual localization and it works perfectly on the client side (react
+ redux
).
import {APIGatewayEvent, Context, Callback} from 'aws-lambda';
import Language from './pathToModule/Language.ts';
export const api = function(event: APIGatewayEvent, context: Context, callback: Callback)
{
Language.Current = event.headers.cookie.locale;
// do the logic here
}
According to AWS documentation NodeJS instances can be reused for different requests. It means that famous concurrent problems have to be considered, e.g.
Language
.How do you resolve this problem?
For convenience it is good to have only one place for locale change. As I understand the same concern exists for all famous i18n npm packages (i18next, i18n, yahoo i18n, etc).
Upvotes: 0
Views: 2067
Reputation: 9159
There are several solutions:
Node JS container is reused only after a function process is finished (callback
or error
is occurred) (thanks to @idbehold). Thus there is always a unique context per a function call.
Refactor code and pass a locale variable back and force (@Yeshodhan Kulkarni suggestion).
For example, return a function as an intermediate result and use it before calling the result back.
var localizableResult = ...;
var result = localizableResult.Localize(requestedLocale)
.
If there is a need to use a local stack (kind of a thread context) for other projects there is a npm package node-continuation-local-storage.
Case 1
makes it really simple to use global variables for current locale.
Upvotes: 0
Reputation: 2943
One of the best practices for Lambda functions is to try and not write code which maintains state.
Here you are initializing the locale based on an initial request and applying it to all future requests, which is inherently flawed even on server based code, forget server less.
To fix this, you will need to initialize the localization library for each request, or at least maintain an in memory lazy map, which you can make use of use the current request's locale to achieve the desired localization.
Upvotes: 1