insomnia/plugins/insomnia-plugin-prompt/index.js

75 lines
2.3 KiB
JavaScript
Raw Normal View History

2018-06-27 05:12:43 +00:00
module.exports.requestHooks = [
context => {
2018-06-27 05:12:43 +00:00
const requestId = context.request.getId();
2018-06-27 05:12:43 +00:00
// Delete cached values we prompt again on the next request
context.store.clear();
}
];
2018-06-25 17:42:50 +00:00
module.exports.templateTags = [
{
displayName: 'Prompt',
name: 'prompt',
description: 'prompt user for input',
args: [
{
displayName: 'Title',
2018-06-27 05:12:43 +00:00
type: 'string',
help: 'Title is a unique string used to identify the prompt value',
validate: v => (v ? '' : 'Required')
2018-06-25 17:42:50 +00:00
},
{
displayName: 'Label',
type: 'string'
},
{
displayName: 'Default Value',
type: 'string',
help:
'This value is used to pre-populate the prompt dialog, but is ALSO used ' +
'when the app renders preview values (like the one below). This is to prevent the ' +
'prompt from displaying too frequently during general app use.'
},
{
displayName: 'Storage Key',
type: 'string',
help:
'If this is set, the value will be stored in memory under this key until the app is ' +
"closed. To force this tag to re-prompt the user, simply change this key's value to " +
'something else.'
}
],
async run(context, title, label, defaultValue, explicitStorageKey) {
2018-06-27 05:12:43 +00:00
if (!title) {
throw new Error('Title attribute is required for prompt tag');
}
// If we don't have a key, default to request ID.
// We do this because we may render the prompt multiple times per request.
// We cache it under the requestId so it only prompts once. We then clear
// the cache in a response hook when the request is sent.
2018-06-27 05:12:43 +00:00
const storageKey =
explicitStorageKey || `${context.meta.requestId}.${title}`;
const cachedValue = await context.store.getItem(storageKey);
if (cachedValue) {
2018-06-25 17:42:50 +00:00
console.log(`[prompt] Used cached value under ${storageKey}`);
return cachedValue;
2018-06-25 17:42:50 +00:00
}
2018-06-25 17:42:50 +00:00
const value = await context.app.prompt(title || 'Enter Value', {
label,
defaultValue
});
2018-06-25 17:42:50 +00:00
if (storageKey) {
console.log(`[prompt] Stored value under ${storageKey}`);
await context.store.setItem(storageKey, value);
2018-06-25 17:42:50 +00:00
}
2018-06-25 17:42:50 +00:00
return value;
}
}
2018-06-25 17:42:50 +00:00
];