在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:webpro/dyson开源软件地址:https://github.com/webpro/dyson开源编程语言:JavaScript 100.0%开源软件介绍:dysonNode server for dynamic, fake JSON. IntroductionDyson allows you to define JSON endpoints based on a simple # my-stubs/users.js
module.exports = {
path: '/users/:userId',
template: {
id: params => Number(params.userId),
name: () => faker.name.findName(),
email: () => faker.internet.email(),
status: (params, query) => query.status,
lorem: true
}
}; $ dyson ./my-stubs
$ curl http://localhost:3000/users/1?status=active {
"id": 1,
"name": "Josie Greenfelder",
"email": "[email protected]",
"status": "active",
"lorem": true
} When developing client-side applications, often either static JSON files, or an actual server, backend, datastore, or API, is used. Sometimes static files are too static, and sometimes an actual server is not available, not accessible, or too tedious to set up. This is where dyson comes in. Get a full fake server for your application up and running in minutes. Overview
Endpoint ConfigurationConfigure endpoints using simple objects: module.exports = {
path: '/user/:id',
method: 'GET',
template: {
id: (params, query, body) => params.id,
name: g.name,
address: {
zip: g.zipUS,
city: g.city
}
}
}; The The
Note: the DefaultsThe default values for the configuration objects: module.exports = {
cache: false,
delay: false,
proxy: false,
size: () => _.random(2, 10),
collection: false,
callback: response.generate,
render: response.render
};
Fake data generatorsYou can use anything to generate data. Here are some suggestions: Just install the generator(s) in your project to use them in your templates: npm install dyson-generators --save-dev ContainersContainers can help if you need to send along some meta data, or wrap the response data in a specific way. Just use the module.exports = {
path: '/users',
template: user.template,
container: {
meta: (params, query, data) => ({
userCount: data.length
}),
data: {
all: [],
the: {
way: {
here: (params, query, data) => data
}
}
}
}
}; And an example response: {
"meta": {
"userCount": 2
},
"data": {
"all": [],
"the": {
"way": {
"here": [
{
"id": 412,
"name": "John"
},
{
"id": 218,
"name": "Olivia"
}
]
}
}
}
} Combined requestsBasic support for "combined" requests is available, by means of a comma separated path fragment. For example, a request to The Status codesBy default, all responses are sent with a status code This can be overridden with your own module.exports = {
path: '/feature/:foo?',
status: (req, res, next) => {
if (req.params.foo === '999') {
res.status(404);
}
next();
}
}; Would result in a ImagesIn addition to configured endpoints, dyson registers a dummy image service at This service is a proxy to Dynamic Dummy Image Generator by Russell Heimlich. JSONPOverride the module.exports = {
render: (req, res) => {
const callback = req.query.callback;
if (callback) {
res.append('Content-Type', 'application/javascript');
res.send(`${callback}(${JSON.stringify(res.body)});`);
} else {
res.send(res.body);
}
}
}; File UploadEx: return file name module.exports = {
render: (req, res) => {
if (callback) {
res.send({ fileName: req.files.file.name });
} else {
res.send(res.body);
}
}
}; HTTPSIf you want to run dyson over SSL you have to provide a (authority-signed or self-signed) certificate into the const fs = require('fs');
const app = dyson.createServer({
configDir: `${__dirname}/dummy`,
port: 3001,
https: {
key: fs.readFileSync(`${__dirname}'/certs/sample.key`),
crt: fs.readFileSync(`${__dirname}/certs/sample.crt`)
}
}); Note: if running SSL on port 443, it will require GraphQLIf you want dyson to support GraphQL endpoints, you can build your own logic with the npm install dyson-graphql --save-dev const dysonGraphQl = require('dyson-graphql');
const schema = `
type User {
id: Int!
name: String!
}
type Query {
currentUser: User!
}
type Mutation {
createUser(name: String!): User!
updateUser(id: Int!, name: String!): User!
}
`;
module.exports = {
path: '/graphql',
method: 'POST',
render: dysonGraphQl(schema)
.query('currentUser', { id: 987, name: 'Jane Smart' })
.mutation('createUser', ({ name }) => ({ id: 456, name }))
.mutation('updateUser', ({ id, name }) => {
if (id < 1000) {
return { id, name };
}
throw new Error("Can't update user");
})
.build()
}; Custom middlewareIf you need some custom middleware before or after the endpoints are registered, dyson can be initialized programmatically.
Then you can use the Express server instance ( const dyson = require('dyson');
const path = require('path');
const options = {
configDir: path.join(__dirname, 'services'),
port: 8765
};
const configs = dyson.getConfigurations(options);
const appBefore = dyson.createServer(options);
const appAfter = dyson.registerServices(appBefore, options, configs);
console.log(`Dyson listening at port ${options.port}`); Dyson configuration can also be installed into any Express server: const express = require('express');
const dyson = require('./lib/dyson');
const path = require('path');
const options = {
configDir: path.join(__dirname, 'services')
};
const myApp = express();
const configs = dyson.getConfigurations(options);
dyson.registerServices(myApp, options, configs);
myApp.listen(8765); InstallationThe recommended way to install dyson is to install it locally and put it in your npm install dyson --save-dev Then you can use it from {
"name": "my-package",
"version": "1.0.0",
"scripts": {
"mocks": "dyson mocks/"
}
} You can also install dyson globally to start it from anywhere: npm install -g dyson ProjectYou can put your configuration files anywhere. The HTTP method is based on:
dyson [dir] This starts the services configured in You can also provide an alternative port number by just adding it as a second argument (e.g. Demo
Project ConfigurationOptionally, you can put a {
"multiRequest": ",",
"proxy": true,
"proxyHost": "http://dyson.jit.su",
"proxyPort": 8080,
"proxyDelay": [200, 800]
}
Watch/auto-restartIf you want to automatically restart dyson when you change your configuration objects, you can add nodemon as a
Development & run testsgit clone [email protected]:webpro/dyson.git
cd dyson
npm install
npm test Articles about dyson
License |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论