Send response: Microservice

This is more server-side, not spigot-server, but server-server, as in microservice-server, get it? Yeah, me neither

Example for making your first request

In this class, I will demonstrate the usage of all four HTTP methods. If you have previous experience with microservices, the material should be easily comprehensible.

Information

This code fetches player data from MySQL for Spigot via a GET request with UUID as parameter. The SQL query selects the player record and returns first result as player data. Additional functionality such as inserting records recommended.

Service files are usually nested in the /service(s)/* folder in your app. Files that end with .service.ts, hold the logic for when they get requested from our Spigot server.

service/player.service.ts
import { Router } from '@spigotmc/microservice';
import { connection } from '..';

/**
 * Create a new router for this service.
 */
const service = new Router();

/**
 * This is only one example of four methods
 */
service.get('/load', (query) => {
  /**
   * The UUID of the player gets passed through
   * the query because this is a GET request.
   */
  const uuid: string = query.uuid;

  /**
   * This is the query that gets executed.
   */
  const sql = `SELECT * FROM players WHERE uuid='${}'`;

  /**
   * Execute the query and wait for the result.
   */
  return new Promise((resolve, reject) => {
    connection.query(sql, (error, results) => {
      /**
       * Reject the promise if an error occured.
       */
      if (error) return reject(error);
      /**
       * Resolve the promise with player's data.
       */
      resolve();
    });
  });
});

/**
 * Other endpoints like `/coin_update`, etc.,
 * should be implemented in this same file.
 */
export { service as playerService };

Once you made your first service file, you should import this in the /api router.

routes.ts
import { Router } from '@spigotmc/microservice';
import { playerService } from './services/player.service';

/**
 * Create a new Router from the Microservice library.
 */ 
const router = new Router();

/**
 * 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.
 */ 
export default router;

Last updated