Is there a way to retrieve the value of an option passed by serverless CLI in serverless.ts file?

As I explored the serverless framework with serverless.ts for configuration, a certain question came to mind.

When utilizing the serverless CLI, passing values can be done in the following way:

serverless offline --stage prod

In the serverless.yml file, accessing this value is possible using ${self:provider.stage}. However, I encountered difficulty attempting to access this passed value in serverless.ts.

While I understand that it can be replaced with a constant variable or not passed via the CLI, my curiosity remains whether there is any method to access the passed value in serverless.ts. Any insights on this issue?

Answer №1

In summary: I found a workaround by utilizing the function exported in

serverless/lib/utils/resolveCliInput
.

If I understand your question correctly, you are looking for a way to access values passed to serverless CLI from within serverless.(ts|js). In my case, I encountered this issue and struggled to find a solution through searching online. Eventually, I delved into the serverless source code and came across a file called

serverless/lib/utils/resolveCliInput
which contains a function that resolves input arguments.

Although I can't guarantee the stability of this method in future versions of the framework (tested on version 2.8.0), here is an example of working code:

import resolveCliInput from 'serverless/lib/utils/resolveCliInput';
const { commands, options } = resolveCliInput(process.argv.slice(2));
const stage = options.s ?? options.stage ?? 'dev';

Alternatively, we could use a library like commander for parsing process.argv, or handle argument parsing directly in our code.

Answer №2

The value you are currently using is not correct, ${self:provider.stage} should refer to the value within the provider key in your configuration file (self.provider):

const serverlessConfiguration: AWS = {
  service: 'hexagonal-serverless-workshop',
  frameworkVersion: '3',
  plugins: ['serverless-esbuild'],
  provider: { // <--- HERE
    name: 'aws',
    runtime: 'nodejs14.x',
    stage: 'dev',
    httpApi: {
      cors: true,
    },
    apiGateway: {
      minimumCompressionSize: 1024,
      shouldStartNameWithService: true,
    },
    environment: {
      AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
      NODE_OPTIONS: '--enable-source-maps --stack-trace-limit=1000',
    },
  },
 ...
}

The correct notation for setting up the stage as prod would be --stage prod and can be accessed using ${opt:stage}.

To ensure you get the appropriate stage value, it's recommended to use a conditional statement like

${opt:stage, self:provider.stage, 'dev'}

This approach will check if the stage value is provided as an option, if not it will fall back to the value defined in the configuration, and finally default to 'dev' if no values are present.

For more detailed information, please refer to:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective way to determine the data type of a value associated with a key in an interface?

In my TypeScript interface, I have defined the following structure: MyInterface { 'key1': number | string; 'key2': string; 'key3': SomeOtherInterface; } I am looking to create a new type that utilizes the properties of ...

Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty. Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding ...

Troubleshooting ion-radio loop error in Ionic 2

I am encountering an issue with the ion-radio component in Ionic 2. The problem is that when the component retrieves data from a service using HTTP and assigns it to the data property within the ngOnInit lifecycle hook, the radio buttons are not able to b ...

Incorporating a particular JavaScript library into Angular 4 (in case the library doesn't have a variable export)

I am attempting to display the difference between two JSON objects in an Angular 4 view. I have been using a library called angular-object-diff, which was originally created for AngularJS. You can view a demo of this library here: Link I have trie ...

Working with TypeScript to set a value for an object's field

I have two objects of the same model: interface Project { _id?: string title: string description: string goal: string tasks?: Task[] createdAt?: Date updatedAt?: Date } The first object contains all fields from the interface, while the secon ...

When invoking the function, the original state remains unaffected within a separate function

Whenever I click on an 'item', it should establish an initial value for me to use in a comparison within another function that involves the mousemove event. However, when the mousemove function is triggered, the initial state remains at 0. imp ...

Creating a custom Higher Order Component to seamlessly connect react-relay and react-router using TypeScript

Hey there! So, my Frankenstein monster project has decided to go rogue and I'm running out of hair to pull out. Any help would be greatly appreciated. I've been working on setting up a simple app with React, React-Router, React-Relay, and Typesc ...

Animating multiple elements in Angular 2 using a single function

Currently, I am delving into Angular and faced a challenge while attempting to create a toggle categories menu. Within my navbar component, I have an animation trigger set up as follows: trigger('slideCategory', [ state('opened&apo ...

Is this Firebase regulation accurate and suitable for PUT and GET requests in an Angular and Firebase environment?

Creating a system where users can only see their own posts and no one else can access them is my main goal. Authentication along with posting functionality is already in place and working, but I want to implement this without using Firebase restrictions. ...

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...

`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The b ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...

Is there a way to customize the Color Palette in Material UI using Typescript?

As a newcomer to react and typescript, I am exploring ways to expand the color palette within a global theme. Within my themeContainer.tsx file, import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme'; declare module '@mate ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Ways to implement material-ui button design on an HTML-native button

I am using pure-react-carousel which provides me an unstyled HTML button (ButtonBack). I would like to customize its style using material-ui. Trying to nest buttons within buttons is considered not allowed. An approach that works is manually assigning th ...

Utilizing React forwardRef with a functional component

Looking at my code, I have defined an interface as follows: export interface INTERFACE1{ name?: string; label?: string; } Additionally, there is a function component implemented like this: export function FUNCTION1({ name, label }: INTERFACE1) { ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

Ensuring the correctness of environment variables in Next.js using Zod

After spending the entire day trying to figure it out, I realize that the solution may be simpler than expected. I am currently using the well-known zod library to validate my environment variables and transform data. However, I keep encountering a persis ...

There is no overload that matches this call in Next.js/Typescript

I encountered a type error stating that no overload matches this call. Overload 1 of 3, '(props: PolymorphicComponentProps<"web", FastOmit<Omit<AnchorHTMLAttributes, keyof InternalLinkProps> & InternalLinkProps & { ...; ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...