mock-config-server
Advanced tools
Comparing version 3.6.1 to 3.7.0
export * from './user'; | ||
export * from './users'; |
@@ -0,0 +0,0 @@ import type { GraphQLRequestConfig } from 'mock-config-server'; |
@@ -0,0 +0,0 @@ import type { GraphQLRequestConfig } from 'mock-config-server'; |
export * from './user'; | ||
export * from './users'; |
@@ -0,0 +0,0 @@ import type { RestRequestConfig } from 'mock-config-server'; |
@@ -0,0 +0,0 @@ import type { RestRequestConfig } from 'mock-config-server'; |
export * from './user'; | ||
export * from './users'; |
@@ -0,0 +0,0 @@ import type { GraphQLRequestConfig } from 'mock-config-server'; |
@@ -0,0 +0,0 @@ import type { GraphQLRequestConfig } from 'mock-config-server'; |
export * from './user'; | ||
export * from './users'; |
@@ -0,0 +0,0 @@ import type { RestRequestConfig } from 'mock-config-server'; |
@@ -0,0 +0,0 @@ import type { RestRequestConfig } from 'mock-config-server'; |
@@ -93,4 +93,4 @@ import { z } from 'zod'; | ||
})[]; | ||
operationType: "query" | "mutation"; | ||
operationName: string | RegExp; | ||
operationType: "query" | "mutation"; | ||
query?: string | undefined; | ||
@@ -100,4 +100,4 @@ interceptors?: any; | ||
routes: unknown[]; | ||
operationType: "query" | "mutation"; | ||
operationName: string | RegExp; | ||
operationType: "query" | "mutation"; | ||
query?: string | undefined; | ||
@@ -196,4 +196,4 @@ interceptors?: unknown; | ||
operationType: "query" | "mutation"; | ||
operationName?: string | RegExp | undefined; | ||
interceptors?: any; | ||
operationName?: string | RegExp | undefined; | ||
}, { | ||
@@ -203,4 +203,4 @@ query: string; | ||
operationType: "query" | "mutation"; | ||
operationName?: string | RegExp | undefined; | ||
interceptors?: unknown; | ||
operationName?: string | RegExp | undefined; | ||
}>>]>, "many">; | ||
@@ -228,4 +228,4 @@ interceptors: z.ZodOptional<z.ZodPipeline<z.ZodType<unknown, z.ZodTypeDef, unknown>, z.ZodTypeAny>>; | ||
})[]; | ||
operationType: "query" | "mutation"; | ||
operationName: string | RegExp; | ||
operationType: "query" | "mutation"; | ||
query?: string | undefined; | ||
@@ -254,4 +254,4 @@ interceptors?: any; | ||
operationType: "query" | "mutation"; | ||
operationName?: string | RegExp | undefined; | ||
interceptors?: any; | ||
operationName?: string | RegExp | undefined; | ||
})[]; | ||
@@ -258,0 +258,0 @@ interceptors?: any; |
@@ -113,9 +113,9 @@ import { z } from 'zod'; | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
}, { | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -230,9 +230,9 @@ }>, z.ZodObject<{ | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
}, { | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -347,9 +347,9 @@ }>, z.ZodObject<{ | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
}, { | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -464,9 +464,9 @@ }>, z.ZodObject<{ | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
}, { | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -581,9 +581,9 @@ }>, z.ZodObject<{ | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
}, { | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -698,9 +698,9 @@ }>, z.ZodObject<{ | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
}, { | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -734,4 +734,4 @@ }>]>, "many">; | ||
})[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: any; | ||
@@ -744,4 +744,4 @@ }[]; | ||
routes: unknown[]; | ||
method: RestMethod; | ||
path: string | RegExp; | ||
method: RestMethod; | ||
interceptors?: unknown; | ||
@@ -748,0 +748,0 @@ }[]; |
@@ -6,5 +6,5 @@ import type { IRouter } from 'express'; | ||
graphqlConfig: GraphqlConfig; | ||
serverResponseInterceptor?: Interceptors['response']; | ||
serverResponseInterceptor?: Interceptors<'graphql'>['response']; | ||
} | ||
export declare const createGraphQLRoutes: ({ router, graphqlConfig, serverResponseInterceptor }: CreateGraphQLRoutesParams) => IRouter; | ||
export {}; |
@@ -73,5 +73,3 @@ "use strict"; | ||
}); | ||
if (!matchedRouteConfig) { | ||
return next(); | ||
} | ||
if (!matchedRouteConfig) return next(); | ||
if ((_matchedRouteConfig_interceptors = matchedRouteConfig.interceptors) === null || _matchedRouteConfig_interceptors === void 0 ? void 0 : _matchedRouteConfig_interceptors.request) { | ||
@@ -78,0 +76,0 @@ await (0, _helpers.callRequestInterceptor)({ |
@@ -1,3 +0,2 @@ | ||
type Cookies = Record<string, string>; | ||
import type { Cookies } from '../../../../../utils/types'; | ||
export declare const parseCookie: (cookieHeader: string) => Cookies; | ||
export {}; |
@@ -0,1 +1,2 @@ | ||
export * from './contextMiddleware/contextMiddleware'; | ||
export * from './cookieParseMiddleware/cookieParseMiddleware'; | ||
@@ -2,0 +3,0 @@ export * from './corsMiddleware/corsMiddleware'; |
@@ -5,2 +5,3 @@ "use strict"; | ||
}); | ||
_export_star(require("./contextMiddleware/contextMiddleware"), exports); | ||
_export_star(require("./cookieParseMiddleware/cookieParseMiddleware"), exports); | ||
@@ -7,0 +8,0 @@ _export_star(require("./corsMiddleware/corsMiddleware"), exports); |
@@ -48,5 +48,6 @@ "use strict"; | ||
} | ||
response.status(404); | ||
const isRequestSupportHtml = ((_request_headers_accept = request.headers.accept) === null || _request_headers_accept === void 0 ? void 0 : _request_headers_accept.includes('text/html')) || ((_request_headers_accept1 = request.headers.accept) === null || _request_headers_accept1 === void 0 ? void 0 : _request_headers_accept1.includes('*/*')); | ||
if (isRequestSupportHtml) { | ||
response.status(404).render('pages/404', { | ||
response.render('pages/404', { | ||
restRequestSuggestions, | ||
@@ -57,3 +58,3 @@ graphqlRequestSuggestions | ||
} | ||
response.status(404).json({ | ||
response.json({ | ||
message: 'Request or page not found. Similar requests in data', | ||
@@ -60,0 +61,0 @@ data: { |
@@ -6,5 +6,5 @@ import type { IRouter } from 'express'; | ||
restConfig: RestConfig; | ||
serverResponseInterceptor?: Interceptors['response']; | ||
serverResponseInterceptor?: Interceptors<'rest'>['response']; | ||
} | ||
export declare const createRestRoutes: ({ router, restConfig, serverResponseInterceptor }: CreateRestRoutesParams) => IRouter; | ||
export {}; |
@@ -58,5 +58,3 @@ "use strict"; | ||
}); | ||
if (!matchedRouteConfig) { | ||
return next(); | ||
} | ||
if (!matchedRouteConfig) return next(); | ||
if ((_matchedRouteConfig_interceptors = matchedRouteConfig.interceptors) === null || _matchedRouteConfig_interceptors === void 0 ? void 0 : _matchedRouteConfig_interceptors.request) { | ||
@@ -63,0 +61,0 @@ await (0, _helpers.callRequestInterceptor)({ |
@@ -35,2 +35,3 @@ "use strict"; | ||
server.use(_bodyparser.default.text()); | ||
(0, _middlewares.contextMiddleware)(server); | ||
(0, _middlewares.cookieParseMiddleware)(server); | ||
@@ -37,0 +38,0 @@ const serverRequestInterceptor = (_databaseMockServerConfig_interceptors = databaseMockServerConfig.interceptors) === null || _databaseMockServerConfig_interceptors === void 0 ? void 0 : _databaseMockServerConfig_interceptors.request; |
@@ -36,2 +36,3 @@ "use strict"; | ||
server.use(_bodyparser.default.text()); | ||
(0, _middlewares.contextMiddleware)(server); | ||
(0, _middlewares.cookieParseMiddleware)(server); | ||
@@ -38,0 +39,0 @@ const serverRequestInterceptor = (_graphqlMockServerConfig_interceptors = graphqlMockServerConfig.interceptors) === null || _graphqlMockServerConfig_interceptors === void 0 ? void 0 : _graphqlMockServerConfig_interceptors.request; |
@@ -37,2 +37,3 @@ "use strict"; | ||
server.use(_bodyparser.default.text()); | ||
(0, _middlewares.contextMiddleware)(server); | ||
(0, _middlewares.cookieParseMiddleware)(server); | ||
@@ -39,0 +40,0 @@ const serverRequestInterceptor = (_mockServerConfig_interceptors = mockServerConfig.interceptors) === null || _mockServerConfig_interceptors === void 0 ? void 0 : _mockServerConfig_interceptors.request; |
@@ -36,2 +36,3 @@ "use strict"; | ||
server.use(_bodyparser.default.text()); | ||
(0, _middlewares.contextMiddleware)(server); | ||
(0, _middlewares.cookieParseMiddleware)(server); | ||
@@ -38,0 +39,0 @@ const serverRequestInterceptor = (_restMockServerConfig_interceptors = restMockServerConfig.interceptors) === null || _restMockServerConfig_interceptors === void 0 ? void 0 : _restMockServerConfig_interceptors.request; |
@@ -25,3 +25,3 @@ "use strict"; | ||
const server = mockServer.listen(port, ()=>{ | ||
console.log(_ansicolors.default.green(`🎉 Database Mock Server is running at http://localhost:${port}`)); | ||
console.info(_ansicolors.default.green(`🎉 Database Mock Server is running at http://localhost:${port}`)); | ||
}); | ||
@@ -28,0 +28,0 @@ // ✅ important: add destroy method for closing keep-alive connections after server shutdown |
@@ -25,3 +25,3 @@ "use strict"; | ||
const server = mockServer.listen(port, ()=>{ | ||
console.log(_ansicolors.default.green(`🎉 GraphQL Mock Server is running at http://localhost:${port}`)); | ||
console.info(_ansicolors.default.green(`🎉 GraphQL Mock Server is running at http://localhost:${port}`)); | ||
}); | ||
@@ -28,0 +28,0 @@ // ✅ important: add destroy method for closing keep-alive connections after server shutdown |
@@ -25,3 +25,3 @@ "use strict"; | ||
const server = mockServer.listen(port, ()=>{ | ||
console.log(_ansicolors.default.green(`🎉 Mock Server is running at http://localhost:${port}`)); | ||
console.info(_ansicolors.default.green(`🎉 Mock Server is running at http://localhost:${port}`)); | ||
}); | ||
@@ -28,0 +28,0 @@ // ✅ important: add destroy method for closing keep-alive connections after server shutdown |
@@ -25,3 +25,3 @@ "use strict"; | ||
const server = mockServer.listen(port, ()=>{ | ||
console.log(_ansicolors.default.green(`🎉 Rest Mock Server is running at http://localhost:${port}`)); | ||
console.info(_ansicolors.default.green(`🎉 Rest Mock Server is running at http://localhost:${port}`)); | ||
}); | ||
@@ -28,0 +28,0 @@ // ✅ important: add destroy method for closing keep-alive connections after server shutdown |
export * from './asyncHandler'; | ||
export * from './config'; | ||
export * from './date'; | ||
export * from './entities'; | ||
@@ -10,3 +11,4 @@ export * from './files'; | ||
export * from './isRegExp/isRegExp'; | ||
export * from './logger'; | ||
export * from './sleep'; | ||
export * from './url'; |
@@ -7,2 +7,3 @@ "use strict"; | ||
_export_star(require("./config"), exports); | ||
_export_star(require("./date"), exports); | ||
_export_star(require("./entities"), exports); | ||
@@ -15,2 +16,3 @@ _export_star(require("./files"), exports); | ||
_export_star(require("./isRegExp/isRegExp"), exports); | ||
_export_star(require("./logger"), exports); | ||
_export_star(require("./sleep"), exports); | ||
@@ -17,0 +19,0 @@ _export_star(require("./url"), exports); |
@@ -11,2 +11,3 @@ "use strict"; | ||
}); | ||
const _logger = require("../../logger"); | ||
const _setDelay = require("../helpers/setDelay"); | ||
@@ -18,2 +19,6 @@ const callRequestInterceptor = async (params)=>{ | ||
const getCookie = (name)=>request.cookies[name]; | ||
const log = (logger)=>(0, _logger.callRequestLogger)({ | ||
logger, | ||
request | ||
}); | ||
const requestInterceptorParams = { | ||
@@ -24,5 +29,6 @@ request, | ||
getHeaders, | ||
getCookie | ||
getCookie, | ||
log | ||
}; | ||
await interceptor(requestInterceptorParams); | ||
}; |
@@ -11,2 +11,3 @@ "use strict"; | ||
}); | ||
const _logger = require("../../logger"); | ||
const _setDelay = require("../helpers/setDelay"); | ||
@@ -40,2 +41,8 @@ const callResponseInterceptors = async (params)=>{ | ||
}; | ||
const log = (logger)=>(0, _logger.callResponseLogger)({ | ||
logger, | ||
data, | ||
request, | ||
response | ||
}); | ||
const responseInterceptorParams = { | ||
@@ -53,3 +60,4 @@ request, | ||
clearCookie, | ||
attachment | ||
attachment, | ||
log | ||
}; | ||
@@ -56,0 +64,0 @@ let updatedData = data; |
@@ -7,3 +7,2 @@ export type CheckActualValueCheckMode = 'exists' | 'notExists'; | ||
export type CheckMode = CheckActualValueCheckMode | CompareWithDescriptorValueCheckMode | CalculateByDescriptorValueCheckMode; | ||
export type PlainEntityCheckMode = Exclude<CheckMode, CompareWithDescriptorStringValueCheckMode | Extract<CalculateByDescriptorValueCheckMode, 'regExp'>>; | ||
export interface EntityDescriptor { | ||
@@ -10,0 +9,0 @@ checkMode: CheckMode; |
@@ -9,5 +9,2 @@ import type { Request } from 'express'; | ||
export type GraphQLOperationName = string | RegExp; | ||
export type GraphQLEntityNamesByOperationType = { | ||
[operationType in GraphQLOperationType]: GraphQLEntityName; | ||
}; | ||
export type GraphQLEntitiesByEntityName = { | ||
@@ -36,3 +33,3 @@ [EntityName in GraphQLEntityName]?: GraphQLEntity<EntityName>; | ||
entities?: GraphQLEntitiesByEntityName; | ||
interceptors?: Interceptors; | ||
interceptors?: Interceptors<'graphql'>; | ||
}; | ||
@@ -42,3 +39,3 @@ interface BaseGraphQLRequestConfig { | ||
routes: GraphQLRouteConfig[]; | ||
interceptors?: Interceptors; | ||
interceptors?: Interceptors<'graphql'>; | ||
} | ||
@@ -45,0 +42,0 @@ export interface OperationNameGraphQLRequestConfig extends BaseGraphQLRequestConfig { |
@@ -6,5 +6,7 @@ export * from './checkModes'; | ||
export * from './interceptors'; | ||
export * from './logger'; | ||
export * from './rest'; | ||
export * from './server'; | ||
export * from './shared'; | ||
export * from './utils'; | ||
export * from './values'; |
@@ -10,4 +10,6 @@ "use strict"; | ||
_export_star(require("./interceptors"), exports); | ||
_export_star(require("./logger"), exports); | ||
_export_star(require("./rest"), exports); | ||
_export_star(require("./server"), exports); | ||
_export_star(require("./shared"), exports); | ||
_export_star(require("./utils"), exports); | ||
@@ -14,0 +16,0 @@ _export_star(require("./values"), exports); |
import type { CookieOptions, Request, Response } from 'express'; | ||
import type { Logger, LoggerTokens } from './logger'; | ||
import type { ApiType } from './shared'; | ||
type RequestInterceptorCookieValue = string | undefined; | ||
type RequestInterceptorHeaderValue = string | number | string[] | undefined; | ||
export interface RequestInterceptorParams { | ||
export interface RequestInterceptorParams<Api extends ApiType = ApiType> { | ||
request: Request; | ||
@@ -10,5 +12,6 @@ setDelay: (delay: number) => Promise<void>; | ||
getHeaders: () => Record<string, RequestInterceptorHeaderValue>; | ||
log: (logger?: Logger<'request', Api>) => Partial<LoggerTokens>; | ||
} | ||
export type RequestInterceptor = (params: RequestInterceptorParams) => void | Promise<void>; | ||
export interface ResponseInterceptorParams { | ||
export type RequestInterceptor<Api extends ApiType = ApiType> = (params: RequestInterceptorParams<Api>) => void | Promise<void>; | ||
export interface ResponseInterceptorParams<Api extends ApiType = ApiType> { | ||
request: Request; | ||
@@ -26,8 +29,9 @@ response: Response; | ||
attachment: (filename: string) => void; | ||
log: (logger?: Logger<'response', Api>) => Partial<LoggerTokens>; | ||
} | ||
export type ResponseInterceptor<Data = any> = (data: Data, params: ResponseInterceptorParams) => any; | ||
export interface Interceptors { | ||
request?: RequestInterceptor; | ||
response?: ResponseInterceptor; | ||
export type ResponseInterceptor<Data = any, Api extends ApiType = ApiType> = (data: Data, params: ResponseInterceptorParams<Api>) => any; | ||
export interface Interceptors<Api extends ApiType = ApiType> { | ||
request?: RequestInterceptor<Api>; | ||
response?: ResponseInterceptor<any, Api>; | ||
} | ||
export {}; |
@@ -39,3 +39,3 @@ import type { Request } from 'express'; | ||
entities?: RestEntitiesByEntityName<Method>; | ||
interceptors?: Interceptors; | ||
interceptors?: Interceptors<'rest'>; | ||
}; | ||
@@ -47,3 +47,3 @@ export type RestPathString = `/${string}`; | ||
routes: RestRouteConfig<Method>[]; | ||
interceptors?: Interceptors; | ||
interceptors?: Interceptors<'rest'>; | ||
} | ||
@@ -50,0 +50,0 @@ type RestGetRequestConfig = BaseRestRequestConfig<'get'>; |
@@ -26,3 +26,3 @@ import type { Request } from 'express'; | ||
configs: RestRequestConfig[]; | ||
interceptors?: Interceptors; | ||
interceptors?: Interceptors<'rest'>; | ||
} | ||
@@ -32,3 +32,3 @@ export interface GraphqlConfig { | ||
configs: GraphQLRequestConfig[]; | ||
interceptors?: Interceptors; | ||
interceptors?: Interceptors<'graphql'>; | ||
} | ||
@@ -35,0 +35,0 @@ export type DatabaseConfig = { |
@@ -0,3 +1,10 @@ | ||
/// <reference types="node" /> | ||
import type { ParamsDictionary, Query as ExpressQuery } from 'express-serve-static-core'; | ||
import type { IncomingHttpHeaders } from 'http'; | ||
export type PlainObject = Record<string, any>; | ||
export type Primitive = boolean | number | bigint | string | null | undefined | symbol; | ||
export type Headers = IncomingHttpHeaders; | ||
export type Query = ExpressQuery; | ||
export type Params = ParamsDictionary; | ||
export type Cookies = Record<string, string>; | ||
export type Data = boolean | number | string | any[] | Record<any, any> | null | undefined; |
{ | ||
"name": "mock-config-server", | ||
"version": "3.6.1", | ||
"version": "3.7.0", | ||
"description": "Tool that easily and quickly imitates server operation, create full fake api in few steps", | ||
@@ -5,0 +5,0 @@ "author": { |
381
README.md
@@ -69,17 +69,17 @@ # 🎉 Mock Config Server | ||
- `rest?` Rest configs for mock requests | ||
- `baseUrl?` {string} part of the url that will be substituted at the beginning of rest request url (default: `'/'`) | ||
- `configs` {Array<RestRequestConfig>} configs for mock requests, [read](#configs) | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
- `baseUrl?` `string` part of the url that will be substituted at the beginning of rest request url (default: `'/'`) | ||
- `configs` `Array<RestRequestConfig>` configs for mock requests, [read](#configs) | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
- `graphql?` GraphQL configs for mock requests | ||
- `baseUrl?` {string} part of the url that will be substituted at the beginning of graphql request url (default: `'/'`) | ||
- `configs` {Array<GraphQLRequestConfig>} configs for mock requests, [read](#configs) | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
- `baseUrl?` `string` part of the url that will be substituted at the beginning of graphql request url (default: `'/'`) | ||
- `configs` `Array<GraphQLRequestConfig>` configs for mock requests, [read](#configs) | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
- `database?` Database config for mock requests [read](#database) | ||
- `data` {Object | string} initial data for database | ||
- `routes?` {Object | string} map of custom routes for database | ||
- `staticPath?` {StaticPath} entity for working with static files, [read](#static-path) | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
- `cors?` {Cors} CORS settings object (default: `CORS is turn off`), [read](#cors) | ||
- `port?` {number} server port (default: `31299`) | ||
- `baseUrl?` {string} part of the url that will be substituted at the beginning of the request url (default: `'/'`) | ||
- `data` `Object | string` initial data for database | ||
- `routes?` `Object | string` map of custom routes for database | ||
- `staticPath?` `StaticPath` entity for working with static files, [read](#static-path) | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
- `cors?` `Cors` CORS settings object (default: `CORS is turn off`), [read](#cors) | ||
- `port?` `number` server port (default: `31299`) | ||
- `baseUrl?` `string` part of the url that will be substituted at the beginning of the request url (default: `'/'`) | ||
@@ -90,34 +90,17 @@ ### Configs | ||
##### Rest request config | ||
#### Rest request config | ||
Every route must be configured to handle response content in one of three ways: data or [queue](#polling) or [file](#file-responses). | ||
- `path` {string | RegExp} request path | ||
- `method` {get | post | delete | put | patch | options} rest api method | ||
- `routes` {RestRouteConfig[]} request routes | ||
- `data?` {any} mock data of request | ||
- `queue?` {Array<{ time?: number; data: any}>} queue for polling with opportunity to set time for each response | ||
- `file?` {string} path to file for return in response | ||
- `settings?` {Settings} settings for route (polling on/off, etc.) | ||
- `entities?` Object<headers | cookies | query | params | body> object that helps in data retrieval | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
- `path` `string | RegExp` request path | ||
- `method` `'get' | 'post' | 'delete' | 'put' | 'patch' | 'options'` rest api method | ||
- `routes` `RestRouteConfig[]` request routes | ||
- `data?` `any` mock data of request | ||
- `queue?` `Array<{ time?: number; data: any}>` queue for polling with opportunity to set time for each response | ||
- `file?` `string` path to file for return in response | ||
- `settings?` `Settings` settings for route (polling on/off, etc.) | ||
- `entities?` `Object<headers | cookies | query | params | body>` object that helps in data retrieval | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
##### GraphQL request config | ||
Every route must be configured to handle response content in one of two ways: data or [queue](#polling). | ||
- `operationType` {query | mutation} graphql operation type | ||
- `operationName?` {string | RegExp} graphql operation name | ||
- `query?`: {string} graphql query as string | ||
- `routes` {GraphQLRouteConfig[]} request routes | ||
- `data?` {any} mock data of request | ||
- `queue?` {Array<{ time?: number; data: any}>} queue for polling with opportunity to set time for each response | ||
- `settings?` {Settings} settings for route (polling on/off, etc.) | ||
- `entities?` Object<headers | cookies | query | variables> object that helps in data retrieval | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
- `interceptors?` {Interceptors} functions to change request or response parameters, [read](#interceptors) | ||
> Every graphql config should contain `operationName` or `query` or both of them | ||
##### Rest example | ||
@@ -169,2 +152,19 @@ | ||
#### GraphQL request config | ||
Every route must be configured to handle response content in one of two ways: data or [queue](#polling). | ||
- `operationType` `query | mutation` graphql operation type | ||
- `operationName?` `string | RegExp` graphql operation name | ||
- `query?`: `string` graphql query as string | ||
- `routes` `GraphQLRouteConfig[]` request routes | ||
- `data?` `any` mock data of request | ||
- `queue?` `Array<{ time?: number; data: any}>` queue for polling with opportunity to set time for each response | ||
- `settings?` `Settings` settings for route (polling on/off, etc.) | ||
- `entities?` `Object<headers | cookies | query | variables>` object that helps in data retrieval | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
- `interceptors?` `Interceptors` functions to change request or response parameters, [read](#interceptors) | ||
> Every graphql config should contain `operationName` or `query` or both of them | ||
##### GraphQL example | ||
@@ -325,2 +325,40 @@ | ||
```javascript | ||
/** @type {import('mock-config-server').MockServerConfig} */ | ||
const mockServerConfig = { | ||
rest: { | ||
baseUrl: '/api', | ||
configs: [ | ||
{ | ||
path: '/posts/:postId', | ||
method: 'post', | ||
routes: [ | ||
{ | ||
entities: { | ||
params: { | ||
postId: { | ||
checkMode: 'function', | ||
value: (actualValue) => +actualValue >= 0 && +actualValue <= 50 | ||
}, | ||
}, | ||
cookies: { | ||
authToken: { | ||
checkMode: 'function', | ||
value: (actualValue, checkFunction) => | ||
checkFunction('equals', actualValue, 123) || | ||
checkFunction('startsWith', actualValue, 2) | ||
} | ||
} | ||
}, | ||
data: 'Some user data' | ||
} | ||
] | ||
} | ||
] | ||
} | ||
}; | ||
module.exports = mockServerConfig; | ||
``` | ||
##### Using descriptors for part of REST body or GraphQL variables | ||
@@ -555,4 +593,4 @@ | ||
- `Object<{prefix, path}` | ||
- `prefix` {string} path prefix for request | ||
- `path` {string} path to your static files | ||
- `prefix` `string` path prefix for request | ||
- `path` `string` path to your static files | ||
- `Array<string | Object<{prefix, path}>>` | ||
@@ -564,8 +602,8 @@ | ||
- `origin` {string | RegExp | Array<string | RegExp> | Function | Promise } available origins from which requests can be made | ||
- `methods?` {Array<GET | POST | DELETE | PUT | PATCH>} available methods (default: `GET,OPTIONS,PUT,PATCH,POST,DELETE`) | ||
- `allowedHeaders?` {Array<string>} allowed headers (default: `*`) | ||
- `exposedHeaders?` {Array<string>} exposed headers (default: `*`) | ||
- `credentials?` {boolean} param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`) | ||
- `maxAge?` {number} how long the results can be cached (default: `3600`) | ||
- `origin` `string | RegExp | Array<string | RegExp> | Function | Promise` available origins from which requests can be made | ||
- `methods?` `Array<GET | POST | DELETE | PUT | PATCH>` available methods (default: `GET,OPTIONS,PUT,PATCH,POST,DELETE`) | ||
- `allowedHeaders?` `Array<string>` allowed headers (default: `*`) | ||
- `exposedHeaders?` `Array<string>` exposed headers (default: `*`) | ||
- `credentials?` `boolean` param tells browsers whether to expose the response to the frontend JavaScript code (default: `true`) | ||
- `maxAge?` `number` how long the results can be cached (default: `3600`) | ||
@@ -576,4 +614,4 @@ #### Interceptors | ||
- `request?` (params) => void | ||
- `response?` (data, params) => any | ||
- `request?` `(params) => void` | ||
- `response?` `(data, params) => any` | ||
@@ -586,41 +624,204 @@ > request interceptors (except interceptor for route) are called regardless of whether the server found a route match or not. So changes in request interceptors can affect whether the server finds the route or not | ||
- `request` request object | ||
- `setDelay` (delay) => Promise<void> | ||
- `delay` {number} milliseconds of delay time | ||
- `getHeader` (field) => string | number | string[] | undefined | ||
- `field` {string} name of response header | ||
- `getHeaders` () => Record<string | number | string[] | undefined> | ||
- `getCookie` (name) => string | undefined | ||
- `name` {string} name of cookie | ||
- `setDelay` `(delay) => Promise<void>` | ||
- `delay` `number` milliseconds of delay time | ||
- `getHeader` `(field) => string | number | string[] | undefined` | ||
- `field` `string` name of response header | ||
- `getHeaders` `() => Record<string | number | string[] | undefined>` | ||
- `getCookie` `(name) => string | undefined` | ||
- `name` `string` name of cookie | ||
- `log` `(logger) => Partial<LoggerTokens>` logger function [read](#logger) | ||
- `logger` `Logger | undefined` logger options | ||
##### Response | ||
- `data` {any} mock data of request | ||
- `data` `any` mock data of request | ||
- `params` | ||
- `request` request object | ||
- `response` response object | ||
- `setDelay` (delay) => Promise<void> | ||
- `delay` {number} milliseconds of delay time | ||
- `setStatusCode` (statusCode) => void | ||
- `statusCode` {number} status code for response | ||
- `setHeader` (field, value) => void | ||
- `field` {string} name of response header | ||
- `value` {string | string[] | undefined} value of response header | ||
- `appendHeader` (field, value) => void | ||
- `field` {string} name of response header | ||
- `value` {string | string[] | undefined} value of response header | ||
- `getHeader` (field) => string | number | string[] | undefined | ||
- `field` {string} name of response header | ||
- `getHeaders` () => Record<string | number | string[] | undefined> | ||
- `setCookie` (name, value, options) => void | ||
- `name` {string} name of cookie | ||
- `value` {string} value of cookie | ||
- `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.) | ||
- `getCookie` (name) => string | undefined | ||
- `name` {string} name of cookie | ||
- `clearCookie` (name, options) => void | ||
- `name` {string} name of cookie | ||
- `options` {[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined} cookie options (like path, expires, etc.) | ||
- `attachment` (filename) => void | ||
- `filename` {string} name of file in 'Content-Disposition' header | ||
- `setDelay` `(delay) => Promise<void>` | ||
- `delay` `number` milliseconds of delay time | ||
- `setStatusCode` `(statusCode) => void` | ||
- `statusCode` `number` status code for response | ||
- `setHeader` `(field, value) => void` | ||
- `field` `string` name of response header | ||
- `value` `string | string[] | undefined` value of response header | ||
- `appendHeader` `(field, value) => void` | ||
- `field` `string` name of response header | ||
- `value` `string | string[] | undefined` value of response header | ||
- `getHeader` `(field) => string | number | string[] | undefined` | ||
- `field` `string` name of response header | ||
- `getHeaders` `() => Record<string | number | string[] | undefined>` | ||
- `setCookie` `(name, value, options) => void` | ||
- `name` `string` name of cookie | ||
- `value` `string` value of cookie | ||
- `options` `[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined` cookie options (like path, expires, etc.) | ||
- `getCookie` `(name) => string | undefined` | ||
- `name` `string` name of cookie | ||
- `clearCookie` `(name, options) => void` | ||
- `name` `string` name of cookie | ||
- `options` `[CookieOptions](https://expressjs.com/en/resources/middleware/cookie-session.html) | undefined` cookie options (like path, expires, etc.) | ||
- `attachment` `(filename) => void` | ||
- `filename` `string` name of file in 'Content-Disposition' header | ||
- `log` `(logger) => Partial<LoggerTokens>` logger function [read](#logger) | ||
- `logger` `Logger | undefined` logger options | ||
#### Logger | ||
You can log requests and responses using `log` function in any [interceptor](#interceptors). | ||
`log` has the following signature `(logger?: Logger) => Partial<LoggerTokens>`. | ||
`logger` parameter has the following optional properties | ||
- `options?` `LoggerOptions` object map containing tokens to log. Keys is token names, values is boolean. `true` will add token into log, `false` will remove. If `options` property is not passed, following tokens will be logged | ||
- Request | ||
- type | ||
- id | ||
- timestamp | ||
- method | ||
- url | ||
- Response | ||
- type | ||
- id | ||
- timestamp | ||
- method | ||
- url | ||
- statusCode | ||
- data | ||
- `rewrite?` `(tokens: Partial<LoggerTokens>) => void` function to replace default `console.dir(tokens, { depth: null })` appearance | ||
`log` function returns object with logged token values | ||
```javascript | ||
/** @type {import('mock-config-server').MockServerConfig} */ | ||
const mockServerConfig = { | ||
rest: { | ||
baseUrl: '/api', | ||
configs: [ | ||
{ | ||
path: '/posts', | ||
method: 'get', | ||
routes: [ | ||
{ | ||
interceptors: { | ||
request: ({ log }) => { | ||
log({ // logs following object in terminal | ||
options: { // { | ||
id: true, // id: 1, | ||
type: true, // type: 'request', | ||
timestamp: true, // timestamp: '31.12.2024, 23:59:59,999', | ||
method: true, // method: 'GET', | ||
url: true // url: 'http://localhost:31299/api/rest/posts/1' | ||
} // } | ||
}); | ||
}, | ||
response: (data, { log }) => { | ||
log({ // logs following string in terminal | ||
options: { // response get: http://localhost:31299/api/rest/posts/1 => 200 | ||
type: true, | ||
statusCode: true, | ||
method: true, | ||
url: true | ||
}, | ||
rewrite: ({ type, statusCode, method, url }) => { | ||
console.info(`${type} ${method}: ${url} => ${statusCode}`); | ||
} | ||
}); | ||
return data; | ||
} | ||
} | ||
} | ||
] | ||
} | ||
] | ||
} | ||
}; | ||
export default mockServerConfig; | ||
``` | ||
> By default, `timestamp` and `method` tokens are prettified. | ||
> Timestamp transforms from UNIX-timestamp number to `DD.MM.YYYY, HH:mm:ss,sss` string. | ||
> Method transforms from lower case to upper case. | ||
> If `rewrite` function is used, those tokens will remain unformatted. You can format them as you need. | ||
##### Logger tokens | ||
- `type?` `'request' | 'response'` type of log | ||
- `id?` `number` unique id of request to reference request log with response log | ||
- `timestamp?` `number` UNIX-timestamp in milliseconds | ||
- `method?` `'get' | 'post' | 'delete' | 'put' | 'patch' | 'options'` HTTP method | ||
- `url?` `string` requested URL | ||
- `graphQLOperationType?` `'query' | 'mutation' | null` GraphQL operation type. `null` if request is not GraphQL | ||
- `graphQLOperationName?` `string` GraphQL operation name. `null` if request is not GraphQL | ||
- `graphQLQuery?` `string` GraphQL query. `null` if request is not GraphQL | ||
- `variables?`: `Record<string, any>` GraphQL variables. `null` if request is not GraphQL or variables is not passed | ||
- `headers?` `Record<string, any>` headers object | ||
- `cookies?` `Record<string, any>` cookies object | ||
- `query?` `Record<string, any>` query object | ||
- `params?` `Record<string, any>` params object | ||
- `body?` `any` body | ||
Response logger has additional tokens | ||
- `statusCode?` `number` response status code | ||
- `data?` `any` data returned to client | ||
If you need to log specific properties in mapped entities (headers, cookies, query, params), use `Record<string, boolean>` object instead of boolean. | ||
In that case logger will use following logic: | ||
- if some token is `true`, entity will be filtered by `whitelist` logic. *Only* enabled ones will be logged. | ||
- if all tokens is `false`, entity will be filtered by `blacklist` logic. All entities will be logged *except* disabled ones. | ||
> Whitelist logic have priority over blacklist if you pass `true` and `false` in same entity. | ||
```javascript | ||
/** @type {import('mock-config-server').MockServerConfig} */ | ||
const mockServerConfig = { | ||
rest: { | ||
baseUrl: '/api', | ||
configs: [ | ||
{ | ||
path: '/posts', | ||
method: 'get', | ||
routes: [ | ||
{ | ||
interceptors: { | ||
request: ({ log }) => { | ||
log({ // whitelist. only query1 and query2 will be logged | ||
options: { | ||
query: { | ||
query1: true, | ||
query2: true | ||
} | ||
} | ||
}); | ||
log({ // whitelist. only cookie1 and cookie2 will be logged | ||
options: { | ||
cookies: { | ||
cookie1: true, | ||
cookie2: true, | ||
cookie3: false | ||
} | ||
} | ||
}); | ||
log({ // blacklist. all headers will be logged except header1 | ||
options: { | ||
headers: { | ||
header1: false | ||
} | ||
} | ||
}); | ||
} | ||
}, | ||
data: {} | ||
} | ||
] | ||
} | ||
] | ||
} | ||
}; | ||
export default mockServerConfig; | ||
``` | ||
## Database | ||
@@ -630,4 +831,4 @@ | ||
- `data` {Object | string} initial data for database | ||
- `routes?` {Object | string} map of custom routes for database | ||
- `data` `Object | string` initial data for database | ||
- `routes?` `Object | string` map of custom routes for database | ||
@@ -746,6 +947,6 @@ ### Basic example | ||
- `count` {number} total count of elements | ||
- `pages` {number} count of pages | ||
- `next` {string | null} query string for next link | ||
- `prev` {string | null} query string for prev link | ||
- `count` `number` total count of elements | ||
- `pages` `number` count of pages | ||
- `next` `string | null` query string for next link | ||
- `prev` `string | null` query string for prev link | ||
@@ -828,3 +1029,3 @@ ### Sort | ||
# Init Command | ||
## Init Command | ||
@@ -831,0 +1032,0 @@ The init command is used to initialize a new project or set up the initial configuration for a tool. It helps users get started with a new project by providing a streamlined setup process. |
Sorry, the diff of this file is not supported yet
377599
340
7495
1082