WARNING: THIS APPLICATION IS STILL DEVELOPING!!!
A Koa middleware of mock server to help develop web app.
Gulpfile.js:
import gulp from 'gulp'
import { bodyParser, Koa, LogLevel, createMockServer } from '@whitetrefoil/msm'
gulp.task('backend', (done) => {
const app = new Koa()
console.log('Will use StubAPI mode.')
app.use(bodyParser())
app.use(createMockServer({
// If a request path starts like one of below,
// it will be handled by the mock server,
// otherwise it will call `next()` to pass the request to the next middleware.
apiPrefixes: ['/user-service/', '/auth-service/', '/payment-service/'],
// Where the API definition files locate. Related to PWD.
apiDir : 'myMockFilesInThisDir',
logLevel : LogLevel.WARN,
}))
app.listen(8889, () => {
console.log(`Backend server listening at port 8889`)
done()
})
})
myMockFilesInThisDir/get/user-service/users.json
{
"code" : 200,
"headers": {
"X-My-Custom-Header": "23333333"
},
"body" : {
"_code" : 0,
"_message": "OK",
"data" : [{
"id" : 1,
"name": "Developer 1"
}]
}
}
myMockFilesInThisDir/post/user-service/user/1.js
module.exports = async(ctx, next) => {
await next()
let body = ''
ctx.set('Content-Type', 'text/json; charset=UTF-8')
try {
ctx.status = 200
ctx.body = {
_code : 0,
_message: 'OK',
data : {
id : 1,
name: body.name,
},
}
} catch (e) {
ctx.status = 400
ctx.body = {
_code : 255,
_message: 'Bad JSON format.',
data : {},
}
}
}
Options of MSM middleware
apiDir?: string
- Where the API definition files locate. Related to PWD.apiPrefixes?: string[]
- If a request path starts like one of this, it will be handled by the mock server, otherwise it will callnext()
to pass the request to the next middleware.fallbackToNoQuery?: boolean
- If true (and "ignoreQueries" is nottrue
), when failed to load definition from default location, MSM will do another attempt w/"ignoreQueries": true
. Default tofalse
.ignoreQueries?: string[]|boolean
- Ignore certain search queries when looking up for definitions & recording. Set tofalse
to preserve every search queries. Set totrue
to ignore all. Default totrue
.logLevel?: LogLevel
- Log level. 'INFO' & 'LOG' is the same. Default is 'NONE'. Can be aLogLevel
enum if using TypeScript, otherwise a string like"INFO"
is acceptable.lowerCase?: boolean
- Whether to unify all cases to lower case.nonChar?: string
- Replace/[^a-zA-Z0-9/]/g
to this when looking for API definition files.overwriteMode?: boolean
- Whether to overwrite existing definition file. Only take effect when using "recorder" middleware.ping?: number
- Delay before response, in ms.saveHeaders?: string[]
- Specific some headers to save in "recorder" mode.
Create a Koa compatible MSM middleware.
Use this with the preview server (webpack-serve, webpack-dev-server, etc.) to simulate the backend server.
Create a Koa compatible MSM RECORDER middleware.
Prepend this middleware before normal http-proxy Koa middleware to record the proxied response as JSON definitions.
@whitetrefoil/msm
has ability to handle 2 kind of API definitions:
- JS/TS (Koa middleware function)
- JSON
This is the spec of the API definition files in JSON.
code?: number
- HTTP response status code.headers?: Object
- Custom HTTP response headers.body: any
- Response body. Any valid JSON format can be used.
This module re-exports its koa
& koa-bodyparser
as name Koa
& koaBodyparser
.
This module exports some helper interfaces:
This is the type definition of JSON definition.
Can be used as the type of JS definition, e.g.
import { MsmMiddleware } from '@whitetrefoil/msm'
const middleware: MsmMiddleware = async(ctx, next) => {
// ...
}
The type of ctx
in above MsmMiddleware
.
- Fix "DIR/index" importing problem.
- Fix build process.
- Fix problems of loading JS/TS modules.
- Fix ESM cannot load dir.
- Fix "require is not defined".
- Fix "fs.readFileSync is not a function".
- Optimizations.
- Remove UMD bundle since it's targeting node environment.
- Upgrade infrastructure to support native ESM modules.
- Fix minor TS type issue.
- Fix RegExp error on Windows.
- Upgrade dependencies.
- Export
.d.ts
files.
- Fix wrong version number in README.
- Optimize logs.
- Fix stuff cause json5 def files failed to load.
- Accept JSON5 as def file.
- Clear the whole
process.cwd()
instead of the exact file when requiring JS def file.
- Move "koa" from "devDep" to "dep".
- Upgrade dependencies.
- Fix cannot import js/ts def w/ default export.
- Update README.
- Now gzipped/deflated responses can be recorded correctly.
- Fix
ENOENT
error in recorder mode. - Upgrade many dependencies.
- Put "koa-bodyparser" in "dependencies" instead of "devDependencies".
- Fix the bug cause recorder save definition when the "non-query" version has already existed.
- !!!BREAKING!!! Now in normal mode it will first try to read from path with query preserved. If failed, then try the one without query.
- !!!BREAKING!!!
preserveQuery
option in config is removed due to above.
- Added recorder function.
- !!!BREAKING!!! Migrate the middleware to Koa.
- Export LogLevel enum.
- Fix wrong entry filename.
- Changes many stuff in project infrastructure.
- Fix broken requirements. (Previously put
clear-require
into devDep. but it's actually is a prodReq.)
- Now msm will load latest .js/.ts def file change without need of restarting.
- Small type definition optimize.
- Allow loading
*.ts
definition files when running ints-node
environment.
- Support JSON definition file with comments.
- Re-write logic of definition loader.
- More UT.
- Fix document according to UT finding.
- !!!BREAKING!!! Now the module exports a Class instead of a global object.
- !!!BREAKING!!! Many API changed because of new code design.
- When using simple JSON, include
Content-Type: application/json
by default. - Better TS declarations.
- Be compatible with ES6 export (
export default
).
- Very simple support of log level.
- Fix typo in "README.md".
- Add some new API to help verify http requests during tests.
- Upgraded some dependencies.
- Use
stdout
instead ofstderr
forLogger.warn
&Logger.error
. - Specify the location of
index.d.ts
file inpackage.json
.
- Added a logger helper.
- Upgraded some dependencies.
- Fix some problem related to dependencies.
- Initial release.