APIGit
2024-11-14
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.
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.
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.
Example:
https://your-mockserver.mock.apigit.com/endpoint
https://your-mockserver.mockserver.apigit.com/endpoint
Be sure to update any references in your client applications, documentation, and integrations.
In the old MockServer, several popular JavaScript libraries were globally available, allowing direct usage without explicit imports. These included:
_
) (v4.17.21) - General utility functionsmoment
) (v2.30.1) - Time and date handlingfaker
) (v5.5.3) - Data generatorAjv
) (v6.10.0) - JSON schema validationvalidator
) (v13.12.0) - Validation helperIn the new version of MockServer, these libraries must now be manually imported using require
or import
statements in your mock scripts before use.
require
or import
statements for any supported libraries used in your mock scripts.The new MockServer comes with popular JavaScript libraries pre-installed. Below is a list of supported libraries and examples of how to use them:
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);
});
mock.define()
deprecated, use mock.[get|post|delete|...]()
insteadmock.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.
change all mock.define()
to mock.[get|post|delete|...]()
.
© 2024 APIGit Inc.