Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@ashvajs/mock-server

Package Overview
Dependencies
Maintainers
0
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ashvajs/mock-server - npm Package Compare versions

Comparing version 0.0.7 to 0.0.8

2

package.json
{
"name": "@ashvajs/mock-server",
"version": "0.0.7",
"version": "0.0.8",
"dependencies": {

@@ -5,0 +5,0 @@ "fs": "^0.0.1-security",

@@ -19,2 +19,7 @@ # @ashvajs/mock-server

....v1
......product
........[product] // serves /api/v1/product/[apple|banana|<var>]/list-items
.........list-items
............get.json // serves /api/v1/[apple|banana|any]/list-items [get method]
............post.json // serves /api/v1/[apple|banana|any]/list-items [get method]
......test // route

@@ -34,2 +39,3 @@ ........post.json // serves as /api/v1/test [post method]

## ES6
```

@@ -56,4 +62,26 @@ import path from 'path';

## Javascript
```
const path = require('path');
const express = require('express');
const { MockServer } = require('@ashvajs/mock-server');
const host = process.env.HOST ?? 'localhost';
const port = process.env.PORT ? Number(process.env.PORT) : 3000;
const app = express();
const mockserver = new MockServer(
{
staticApiPath: path.resolve('apps/mock-server-example/mocks'),
},
app
);
mockserver.init();
app.listen(port, host, () => {
console.log(`[ ready ] http://${host}:${port}`);
});
```
## Examples
see `apps/mock-server-example`
declare class MockServer {
config: any;
app: any;
allEndpoints: string[];
fse: any;
constructor({ fse, ...options }: any, app: any);
ensureNoSlash(path: any): any;
ensureNoSlashEnd(path: any): any;
ensureNoSlashStart(path: any): any;
makePath(dir: any, parentPath?: any, _arrPaths?: string[], processPath?: string): string[];
getAllUrls(): Promise<void>;
getFinalPath(url: any): string;
init(): void;
}
export { MockServer };

@@ -16,3 +16,3 @@ "use strict";

}
ensureNoSlash(path) {
ensureNoSlashEnd(path) {
return path.substr(path.length - 1, 1) === '/'

@@ -22,9 +22,75 @@ ? path.substr(0, path.length - 1)

}
ensureNoSlashStart(path) {
return path.substr(0, 1) === '/'
? path.substr(1, path.length - 1)
: `${path}`;
}
makePath(dir, parentPath = this.config.staticApiPath, _arrPaths = [], processPath = '') {
const arrPaths = _arrPaths;
const thisPath = path.join(parentPath, dir);
const pathProcessed = parentPath
? fs.statSync(thisPath).isDirectory() &&
!fs.existsSync(path.join(thisPath, 'index.js'))
? path.join(processPath, dir)
: processPath
: dir;
if (fs.statSync(thisPath).isDirectory()) {
const result = fs.readdirSync(thisPath);
if (result.length > 0) {
result.map((childPath) => {
this.makePath(childPath, thisPath, arrPaths, pathProcessed);
});
}
}
else {
if (arrPaths.indexOf(pathProcessed) === -1) {
arrPaths.push(pathProcessed);
console.log(`created:${pathProcessed}`);
}
}
return arrPaths;
}
getAllUrls() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const result = fs.readdirSync(this.config.staticApiPath);
this.allEndpoints = result.map((path) => this.makePath(path)).flat();
});
}
getFinalPath(url) {
const index = this.allEndpoints.indexOf(url);
let matchedItem = '';
if (index === -1) {
const params = {};
this.allEndpoints.forEach((item) => {
let hasMatch = true;
const leftSide = item.split(path.sep);
const rightSide = url.split('/');
leftSide.forEach((item, idx) => {
if (hasMatch && item.match(new RegExp('\\[.*\\]'))) {
params[item.match(new RegExp('\\[.*\\]'))[1]] = rightSide[idx];
}
else if (hasMatch) {
hasMatch = item === rightSide[idx];
}
});
if (hasMatch) {
matchedItem = item;
}
});
}
if (matchedItem) {
return path.resolve(this.ensureNoSlashEnd(this.config.staticApiPath), matchedItem);
}
return path.resolve(this.ensureNoSlashEnd(this.config.staticApiPath), url);
}
init() {
console.log('--- init mock-server');
this.getAllUrls();
this.app.all(this.config.staticMocks, (req, res) => {
const reqPath = req._parsedUrl.pathname;
const method = req.method.toLowerCase();
let finalPath = reqPath.resolve(this.ensureNoSlash(this.config.staticApiPath), reqPath);
// console.log(finalPath);
const urlToServe = this.ensureNoSlashStart(reqPath);
// console.log(reqPath);
console.log(`looking for=${urlToServe}`);
let finalPath = this.getFinalPath(urlToServe);
let response = new response_1.default(error_1.default.notfound()).error();

@@ -49,4 +115,9 @@ let isJs = false;

else {
response = this.fse.readFileSync(finalPath, 'utf8');
response = JSON.parse(response);
if (fs.existsSync(finalPath)) {
response = this.fse.readFileSync(finalPath, 'utf8');
response = JSON.parse(response);
}
else {
throw `${urlToServe} not found`;
}
}

@@ -53,0 +124,0 @@ if (typeof response === 'function') {

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc