You can utilize the parser's scope to create, modify, and remove variables:
import type {Utilities} from '@parsify/core';
// Why do we use `unknown` here? You will learn in the next sections ;)
const wrapper = (utils: Utilities<unknown>) => {
const plugin = async (expression: string): Promise<string> => {
const {scope} = utils;
// The scope is a JavaScript Map object (<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map>).
// So we can use methods like `set`, `get`, `delete`, etc.
scope.set('x', 12);
scope.get('x'); //=> 12
scope.delete('x');
// Note that this will delete ALL variables AND functions, not only those created by your plugin!
scope.clear();
return expression;
};
return plugin;
};
export default wrapper;
Parser's scope also allows you to define custom functions:
import type {Utilities} from '@parsify/core';
const wrapper = (utils: Utilities<unknown>) => {
const plugin = async (expression: string): Promise<string> => {
const {scope} = utils;
scope.set('sayHello', (name: string) => {
return `Hello, ${name}!`;
});
// Now one can do e.g. `sayHello("John");`
return expression;
};
return plugin;
};
export default wrapper;
Do you want to use an online API in your plugin? While you could technically use a package for that (like got
, axios
, node-fetch
, or isomorphic-unfetch
), we highly recommend to utilize the built-in fetcher utility. It is based on the familiar Fetch API and optimized for Parsify Desktop (for example, it handles offline scenarios and DNS-level caching).
It currently only supports requests that return the response in the JSON format. If you use case requires a non-JSON API, please contact us with some details to share your interest in extending the functionality.
<aside> ⚠️ Please note that fetching online data is not yet optimized and, thus, may slow down some calculations.
</aside>
import type {Utilities} from '@parsify/core';
const API = '<https://zenquotes.io/api/random>';
// Optional: use this argument to type the expected response.
const wrapper = (utils: Utilities<{q: string}>) => {
const plugin = async (expression: string): Promise<string> => {
const {fetcher} = utils;
const response = await fetcher(API);
if (expression === 'qotd') {
// JSON serialization is handled automatically.
return response.q;
}
return expression;
};
return plugin;
};
export default wrapper;