MockServer Migration Guide

APIGit

2024-11-14

APIGIT MockServer Migration Guide

Introduction

On November 9, 2024, APIGIT officially launched a new version of the MockServer backend, powered by Express.js and running in a Node.js sandbox environment. This version brings improved features, enhanced flexibility, and a more robust way to define mock server behaviors. However, transitioning from the old version (pure JavaScript-based) to the new one requires addressing some breaking changes.

This guide will help you understand these changes, adapt your existing mock server projects, and ensure a seamless migration to the new MockServer.

Key Changes and Migration Details

The new MockServer has introduced a few breaking changes compared to the old version. It's important to be aware of these changes and adapt your projects accordingly.

1. URL Change for Mock Servers

Old URL format: your-mockserver.mock.apigit.com

New URL format: your-mockserver.mockserver.apigit.com

If you have not republished your mock server since the new MockServer launch, the old mock server will continue to work until the end of the year. However, if you decide to republish your mock server using the same mockserver name, you will need to update any existing references to reflect the new URL structure.

What You Need to Do:

  • If your mock server is still using the old URL, no immediate changes are required, and it will remain operational until December 31, 2024.
  • If you republish your mock server, ensure that all endpoints, configurations, and references in your applications are updated to use the new URL of the mockserver.

Example:

  • Old URL: https://your-mockserver.mock.apigit.com/endpoint
  • New URL: https://your-mockserver.mockserver.apigit.com/endpoint

Be sure to update any references in your client applications, documentation, and integrations.

2. Library Imports - No More Global Libraries Variables

In the old MockServer, several popular JavaScript libraries were globally available, allowing direct usage without explicit imports. These included:

  • lodash (_) (v4.17.21) - General utility functions
  • momentjs (moment) (v2.30.1) - Time and date handling
  • faker (faker) (v5.5.3) - Data generator
  • ajv (Ajv) (v6.10.0) - JSON schema validation
  • validator (validator) (v13.12.0) - Validation helper

In the new version of MockServer, these libraries must now be manually imported using require or import statements in your mock scripts before use.

What You Need to Do:

  • Add appropriate require or import statements for any supported libraries used in your mock scripts.

Supported Libraries in the New MockServer

The new MockServer comes with popular JavaScript libraries pre-installed. Below is a list of supported libraries and examples of how to use them:

  • @faker-js/faker (v9.2.0) - Data generator
  • ajv (v8.17.1) - JSON schema validation
  • base64-js (v1.5.1) - Base64 encoding/decoding
  • cors (v2.8.5) - Cross-Origin Resource Sharing middleware
  • jsonwebtoken (v9.0.2) - JWT creation and verification
  • lodash (v4.17.21) - General utility
  • moment (v2.30.1) - Time and date handling
  • uuid (v11.0.3) - UUID generator
  • validator (v13.12.0) - Validation helper

Example Usage:

var moment = require('moment'); // require
const { faker } = require('@faker-js/faker');
const Ajv = require("ajv");
var validator = require('validator');
const base64 = require('base64-js');
const jwt = require('jsonwebtoken');
const { v4: uuidv4 } = require('uuid');
const _ = require('lodash');

function testLodash() {
  // Test data
  const users = [
    { id: 1, name: 'Alice', age: 25, active: true },
    { id: 2, name: 'Bob', age: 30, active: false },
    { id: 3, name: 'Charlie', age: 35, active: true },
    { id: 4, name: 'David', age: 40, active: false }
  ];

  // Example 1: Filter active users
  const activeUsers = _.filter(users, { active: true });
  console.log('Active Users:', activeUsers);

  // Example 2: Sort users by age in descending order
  const sortedByAge = _.orderBy(users, ['age'], ['desc']);
  console.log('Users sorted by age (desc):', sortedByAge);

  // Example 3: Get the names of all users
  const userNames = _.map(users, 'name');
  console.log('User Names:', userNames);
}

function testMoment() {
  console.log("Current time is:", moment().format());
}

function testUuidv4() {
  console.log("UUID is:", uuidv4());
}

function testAjv() {
  const ajv = new Ajv();
  const schema = {
    type: "object",
    properties: {
      foo: { type: "integer" },
      bar: { type: "string" },
    },
    required: ["foo"],
    additionalProperties: false,
  };
  const data = { foo: 1, bar: "abc" };
  const validate = ajv.compile(schema);
  const valid = validate(data);
  if (!valid) console.log(validate.errors);
}

function testBase64() {
  const text = 'Hello, world!';
  const textBytes = new TextEncoder().encode(text);
  const base64Encoded = base64.fromByteArray(textBytes);
  console.log('Base64 Encoded:', base64Encoded);

  const decodedBytes = base64.toByteArray(base64Encoded);
  const decodedText = new TextDecoder().decode(decodedBytes);
  console.log('Decoded Text:', decodedText);
}

function testValidator() {
  const result = validator.isEmail('fooo~bar.com');
  console.log("fooo~bar.com is email, right?", result);
}

function testFakerJS() {
  return {
    userId: faker.string.uuid(),
    username: faker.internet.username(),
    email: faker.internet.email(),
    avatar: faker.image.avatar(),
    password: faker.internet.password(),
    birthdate: faker.date.birthdate(),
    registeredAt: faker.date.past(),
  };
}

function testJwt() {
  const SECRET_KEY = 'your-secret-key';
  const payload = { userId: 123, username: 'testUser' };
  const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });
  console.log('Generated Token:', token);
  try {
    const decoded = jwt.verify(token, SECRET_KEY);
    console.log('Decoded Payload:', decoded);
  } catch (err) {
    console.error('Token verification failed:', err.message);
  }
}

mock.get("/testlibs", function (req, res) {
  console.log("==== this is a test of libs supported =====");
  testLodash();
  testMoment();
  testUuidv4();
  testAjv();
  testValidator();
  testBase64();
  testJwt();
  const jsonData = testFakerJS();
  return res.status(200).json(jsonData);
});

3. mock.define() deprecated, use mock.[get|post|delete|...]() instead

mock.define() is deprecated in this new mockserver. Please use mock.[get|post|delete|...]() instead, which is the native way of express.js to define routes. Please be noted that mock.define() is still available, but it will stop support in future.

What You Need to Do:

change all mock.define() to mock.[get|post|delete|...]().