Reduce Boilerplate with yargs middleware in a Node.js Command Line Tool

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Sometimes you might want to transform arguments before they reach the command handler. For example, perhaps you want to validate that credentials have been provided and otherwise load credentials from a file.

Middleware is simply a stack of functions, each of which is passed the current parsed arguments, which it can in turn update by adding values, removing values, or overwriting values.

Instructor: [00:00] Here, we have a simple command-line tool written with Yargs. We are defining our first command called lesson. When we call back, we will output this to the console. Let's test this. Indeed, we can see our lessons. We would like to protect these lessons behind a secret. Only when the user provides the secret, we will show these lessons.

[00:28] First thing, we need to define option. Here, we can do Yargs options. We call our option secret. Second, we define our secret that we will test against. For now, it will be egghead. If secrets don't match, we will throw an error.

[00:55] Let's test this. We can see here, it's access denied. If we provide the secret, we can see the lessons again. Now, I'd like to add courses command. Let's check for the secret. If we test here, we can see the access denied error. If we provide the secret, you can see the courses.

[01:27] Let's refactor this a little bit because we have some repetitive codes, mainly this part. We can remove it from here and define a function from the top. We call it check secret that will accept arg B and then throw an error if the secrets don't match. We can remove it also from here.

[01:54] Instead, we check the secret and we question the arg B, and the same for this command. Let's test again. We can see we still see the courses when we provide the secret. Now, if another person comes in and defines a new instructor command, for example, but they actually forget to check for the secrets.

[02:24] Now, we have an expose command, which is instructors. We can enforce that using middleware. We pass in a function check secret. Here, we don't need to call this function explicitly anymore because we'll call it for us every time we call a command.

[02:48] Let's test the instructors command again. We should see the access denied.