You can find a sample repo on GitHub that's using this library, here.
You can really see this as passing JSON object between your server and your microservice, but instead of passing raw JSON, we can serialize and deserialize it into useful objects actually used in your code.
Initialization of the API
Here an example of how to initialize the API on Spigot and how to setup your Node.js environment.
Parameter definitions
Parameter
Type
Default
Description
Creating a new Microservice object
To create a object, we use the ServiceBuilder class.
/** * Initialize it with default values like this; */newServiceBuilder().build();/** * Initialize it with custom values like this; */newServiceBuilder()/* To change default values, add .port(), .()... here. */.host("customhost.com").protocol(Protocol.HTTPS).build();
Establish the host of the API in your Java plugin, which will be utilized for requests.
Plugin.java
importmicro.api.*;publicfinalclassPluginextendsJavaPlugin {publicServiceHost host;publicPlayerRepository repo; @OverridepublicvoidonEnable() {/** * This gives `http://localhost:8080/api` according * to the default values stated here above. */ host =newServiceBuilder().build().getHost(); repo =newPlayerRepository(host); }}
Step 1: Install the Microservice package from NPM:
npminstall@spigotmc/microservice
Or if you're using Yarn:
yarnadd@spigotmc/microservice
Step 2: Initialize a new microservice. Also, don't forget to add your API route.
index.ts
import Microservice from"@spigotmc/microservice";import route from"./routes";/** * MySQL credentials */constmysql= { host:'localhost', port:3306, user:'root', password:'password', database:'minecraft',};/** * Create a new MySQL connection. */exportconstconnection=createConnection(mysql);connection.connect();/** * Create a new Microservice instance. */constservice=Microservice.host(8080);service.setDefiningRoute('/api',route.register());
Step 3: Make a separate file for all your routes to join, then later import that route in your microservice using #setDefiningRoute() as shown above.
Then create a new router and export it when you're finished adding all the sub-routes.
routes.ts
import { Router } from'@spigotmc/microservice';import { playerService } from'./services/player.service';/** * Create a new Router from the Microservice library. */constrouter=newRouter();/** * Add any sub-routes to the main router. */router.use('/player', playerService);/** * Export the router so that we can use * it in the main class where you decl- * ared the microservice. */exportdefault router;
With that, the API has been successfully initialized on both your Java plugin and Node.js platform.