Supported JavaScript libraries
To streamline the process of creating mock server definitions, we've pre-installed popular JavaScript libraries within the mock server sandbox nodejs environment. You can use require
(for .js files) or import
(for .mjs files) to include them directly in your mock server scripts.
The list of supported libraries are:
- @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
If you have a suggestion for a library that is not currently available, contact us (help@apigit.com) to add it.
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() // options can be passed, e.g. {allErrors: true}
const schema = {
type: "object",
properties: {
foo: { type: "integer" },
bar: { type: "string" },
},
required: ["foo"],
additionalProperties: false,
}
const data = {
foo: true,
bar: "abc",
}
const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
}
function testBase64() {
// Example 1: Encode a string to Base64
const text = 'Hello, world!';
const textBytes = new TextEncoder().encode(text); // Convert string to Uint8Array
const base64Encoded = base64.fromByteArray(textBytes); // Encode to Base64
console.log('Base64 Encoded:', base64Encoded);
// Example 2: Decode a Base64 string back to its original format
const decodedBytes = base64.toByteArray(base64Encoded); // Decode to Uint8Array
const decodedText = new TextDecoder().decode(decodedBytes); // Convert Uint8Array to string
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(), // before version 9.1.0, use userName()
email: faker.internet.email(),
avatar: faker.image.avatar(),
password: faker.internet.password(),
birthdate: faker.date.birthdate(),
registeredAt: faker.date.past(),
};
}
function testJwt() {
// Secret key for signing the token
const SECRET_KEY = 'your-secret-key';
// Sample payload
const payload = { userId: 123, username: 'testUser' };
// Create a token
const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '1h' });
console.log('Generated Token:', token);
// Verify the token
try {
const decoded = jwt.verify(token, SECRET_KEY);
console.log('Decoded Payload:', decoded);
} catch (err) {
console.error('Token verification failed:', err.message);
}
}
mock.define("/testlibs", "GET", 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)
});