Extending the plugin

Variables

You can utilize the math parser's scope to create, modify, and remove variables:
1
import type {Utilities} from '@parsify/core';
2
3
// Why do we use `unknown` here? You will learn in the next sections ;)
4
const wrapper = (utils: Utilities<unknown>) => {
5
const plugin = async (expression: string): Promise<string> => {
6
const {scope} = utils;
7
8
// The scope is a JavaScript Map object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map).
9
// So we can use methods like `set`, `get`, `delete`, etc.
10
scope.set('x', 12);
11
scope.get('x'); //=> 12
12
scope.delete('x');
13
14
// Note that this will delete ALL variables AND functions, not only those created by your plugin!
15
scope.clear();
16
17
return expression;
18
};
19
20
return plugin;
21
};
22
23
export default wrapper;
Copied!

Functions

Math parser's scope also allows you to define custom functions:
1
import type {Utilities} from '@parsify/core';
2
3
const wrapper = (utils: Utilities<unknown>) => {
4
const plugin = async (expression: string): Promise<string> => {
5
const {scope} = utils;
6
7
scope.set('sayHello', (name: string) => {
8
return `Hello, ${name}!`;
9
});
10
11
// Now one can do e.g. `sayHello("John");`
12
13
return expression;
14
};
15
16
return plugin;
17
};
18
19
export default wrapper;
Copied!

Fetching online data

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 reponse 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.
Please note that fetching online data is not yet optimized and, thus, may slow down some calculations.
1
import type {Utilities} from '@parsify/core';
2
3
const API = 'https://zenquotes.io/api/random';
4
5
// Optional: use this argument to type the expected response.
6
const wrapper = (utils: Utilities<{q: string}>) => {
7
const plugin = async (expression: string): Promise<string> => {
8
const {fetcher} = utils;
9
10
const response = await fetcher(API);
11
12
if (expression === 'qotd') {
13
// JSON serialization is handled automatically.
14
return response.q;
15
}
16
17
return expression;
18
};
19
20
return plugin;
21
};
22
23
export default wrapper;
Copied!
Last modified 11d ago