Search code examples
monaco-editor

How to read the data inside the web worker?


I'm wondering how to pass the data to Monaco web worker, so this data could then be read from worker code.

The data I'd like to pass are some API endpoints, so the worker could call the APIs:

const worker = monaco.editor.createWebWorker<MyWorkerProxy>({
    moduleId,
    label: languageId,
    createData: {
        languageId,
        apis: { // <-- how to read this data?
            foo: 'http://localhost/foo',
            bar: 'http://localhost/bar'
        }
    }
});

Thanks!


Solution

  • I realized that the 2nd argument of "initialize" method (in worker code) contains the original createData object.

    In order it to be accessible from other parts of the worker code, I've build a small singleton:

    'use strict';
    
    import * as edworker from 'monaco-editor/esm/vs/editor/editor.worker';
    import { MyWorker } from './my-worker';
    import { CreateData, Settings } from './worker-settings';
    
    self.onmessage = (message: any) => {
        edworker.initialize((context: monaco.worker.IWorkerContext, createData: CreateData) => {
            Settings.getInstance().setCreateData(createData); // Singleton
    
            return new MyWorker (context)
        });
    };
    

    So whereever I need to call the API, I do:

    const api = Settings.getInstance().getApis()['foo']
    

    If there is a more elegant way of doing it, it would be great if you could post it here.