For my Visual Studio Code extension to autocomplete the Microsoft Graph APIs, I wanted to improve the speed of the suggestions by implementing a cache. That way, you would not have to do the same API calls each time.
In-memory cache has its limits
Initially, I started with just an in-memory cache. An in-memory cache is easy to establish, but whenever you close your VSCode session. The cache will be gone. Next time, the cache has to be created all from scratch.
What are the options?
Luckily VSCode provides you a couple of options to cache data for your extension. There are two places where you can cache data:
workspaceState
: When you want to cache data for the current workspace/project.globalState
: When you want to cache data independent of your current project.
Both of these states are a Memento
object, which allows you to get
and update
a value.
InfoThere is also a
SecretStorage
which can be used to set/retrieve/delete secrets.
Using the VSCode state
For my extension, I choose to use the globalState
, as I want to cache the Microsoft Graph data independently from the current project. Using the workspaceState
is similar to the globalState
.
Start by creating the cache as follows:
|
|
Once created, you can put data into the cache:
|
|
When you added the data. You can start retrieving it as follows:
|
|
Currently you can only get and update data, you cannot clear/delete the cache. If you can override the cache with a default value.
|
|
InfoYou can find a complete example of using the VSCode state here: CacheProvider.ts.