-
Notifications
You must be signed in to change notification settings - Fork 0
REPL
Immersive provides a repl command:
repl
In repl
mode, you have access to the same context as a command. It means that your helpers are available globally.
See Enhanced context for more information.
Immersive REPL also supports top-level await
& automatically resolves promises.
matthieu:development > repl
> await db.get(1);
{
id: 1,
name: 'John Doe on development',
status: 'VALIDATED',
stars: 5
}
>
In this example, the await
keyword is not required as if your command returns a promise it will be automatically resolved.
matthieu:development > repl
> db.get(1);
{
id: 1,
name: 'John Doe on development',
status: 'VALIDATED',
stars: 5
}
>
REPLs are great when you want to run several commands without losing context between them, when you just want to run quickly a couple of commands or when writing a script isn't worth it.
Immersive provides a convenient REPL command but also a REPL module that you can use if you need more flexibility and to create your own REPL.
Using the REPL module, you can provide a custom evaluation function. For example, you could make a REPL which runs queries against your database without leaving your CLI.
Let's see how we could do that:
// Import the repl module from Immersive
import { repl } from 'immersive';
// Create a Immersive command like you're used to
export const command = 'query';
export const description = 'Query database';
// Call repl in your action with the context provided by Immersive & your custom evaluation function
export const action = context => repl(context, evalQuery)
async function evalQuery(cmd, context, filename, callback) {
// Immersive context
const { logger, db } = context;
// The query entered in the REPL
const query = cmd.trim();
// In this example we only support SELECT queries
if (!query.toLowerCase().startsWith('select')) {
logger.error('Only select queries are supported');
callback(null);
return;
}
// Query your database
const rows = await db.runQuery(query);
logger.info(`${rows.length} rows found`);
// Display the results
logger.table({ rows, name: 'Results' });
// Don't forget to call the callback to be able to enter another query in the REPL
callback(null);
}