UNPKG

9.92 kBMarkdownView Raw
1## Running in mock mode
2
3Mock mode lets you "mock up" API routes/paths and response objects in the Swagger editor and test them without writing any controller code. By default, mock mode responses are system-generated; however, you can optionally implement custom mock controllers to return custom responses.
4
5* [When to use mock mode](#whentouse)
6* [Starting a project in mock mode](#starting)
7* [Quick example: mock mode in action](#quickexample)
8* [Building and testing an API in mock mode](#buildtest)
9* [Implementing mock controllers](#mockcontrollers)
10* [Wiring up and implementing the API controller](#wireup)
11
12### <a name="whentouse"></a>When to use mock mode
13
14Mock mode is useful when you are designing your API model in the Swagger editor, but you're not ready to implement the API's handler/controllers. For example, you might use mock mode when you're trying to decide which API routes you need and what kind of data each API operation should return. Basically, mock mode let's you perfect your API design without writing any Node.js code.
15
16When you're happy with the overall API design, then you can implement your controller methods.
17
18### <a name="starting"></a>Starting a project in mock mode
19
20To start an swagger project in mock mode, use the `-m` flag:
21
22`swagger project start -m`
23
24
25### <a name="quickexample"></a>Quick example: mock mode in action
26
27Here's a simple example where the API definition only has one path (`/weather`) and a response object called WeatherResponse. In this case, the WeatherResponse object returns a simple message of type string. Here's the Swagger YAML:
28
29
30```yaml
31swagger: '2.0'
32info:
33 version: "0.0.1"
34 title: Mock mode test
35host: localhost
36basePath: /
37schemes:
38 - http
39consumes:
40 - application/json
41produces:
42 - application/json
43paths:
44 /weather:
45 get:
46 responses:
47 "200":
48 description: Success
49 schema:
50 $ref: #/definitions/WeatherResponse
51definitions:
52 WeatherResponse:
53 required:
54 - message
55 properties:
56 message:
57 type: string
58```
59
60
61To test this API configuration in mock mode, start your swagger project with the mock mode "-m" flag:
62
63`swagger project start -m`
64
65When you call the API, like this:
66
67`curl -i http://localhost:10010/weather`
68
69Mock mode returns this system-generated response:
70
71
72```json
73 {
74 "message": "Sample text"
75 }
76```
77
78If you change the response object to return an integer...
79
80```yaml
81 WeatherResponse:
82 required:
83 - message
84 properties:
85 message:
86 type: integer
87```
88
89The mock response is an integer:
90
91```json
92 {
93 "message": 1
94 }
95```
96
97
98### <a name="buildtest"></a>Building and testing your API model in mock mode
99
100An actual weather API isn't only going to return a string; it's going to return a more complex response object consisting of objects, strings, and numbers. As you build your API, you can model and test the intended behavior entirely in mock mode.
101
102For example, here's a WeatherResponse object for a weather API. It's got strings, numbers, arrays, and objects representing various aspects of weather data.
103
104```yaml
105 WeatherResponse:
106 properties:
107 base:
108 type: "string"
109 clouds:
110 type: "object"
111 properties:
112 all:
113 type: "number"
114 cod:
115 type: "number"
116 coord:
117 type: "object"
118 properties:
119 lat:
120 type: "number"
121 lon:
122 type: "number"
123 dt:
124 type: "number"
125 id:
126 type: "number"
127 main:
128 type: "object"
129 properties:
130 humidity:
131 type: "number"
132 pressure:
133 type: "number"
134 temp_max:
135 type: "number"
136 temp_min:
137 type: "number"
138 temp:
139 type: "number"
140 name:
141 type: "string"
142 sys:
143 type: "object"
144 properties:
145 country:
146 type: "string"
147 id:
148 type: "number"
149 message:
150 type: "number"
151 sunrise:
152 type: "number"
153 sunset:
154 type: "number"
155 type:
156 type: "number"
157 weather:
158 type: "array"
159 items:
160 type: "object"
161 properties:
162 description:
163 type: "string"
164 icon:
165 type: "string"
166 id:
167 type: "number"
168 main:
169 type: "string"
170 wind:
171 type: "object"
172 properties:
173 deg:
174 type: "number"
175 speed:
176 type: "number"
177```
178
179
180If you call this API in mock mode, it returns the following JSON. Objects, arrays, strings, and numbers are all "mocked up" with mock values of the appropriate data type:
181
182```yaml
183 {
184 "base": "Sample text",
185 "clouds": {
186 "all": 1
187 },
188 "cod": 1,
189 "coord": {
190 "lat": 1,
191 "lon": 1
192 },
193 "dt": 1,
194 "id": 1,
195 "main": {
196 "humidity": 1,
197 "pressure": 1,
198 "temp": 1,
199 "temp_max": 1,
200 "temp_min": 1
201 },
202 "name": "Sample text",
203 "sys": {
204 "country": "Sample text",
205 "id": 1,
206 "message": 1,
207 "sunrise": 1,
208 "sunset": 1,
209 "type": 1
210 },
211 "weather": [
212 {
213 "description": "Sample text",
214 "icon": "Sample text",
215 "id": 1,
216 "main": "Sample text"
217 }
218 ],
219 "wind": {
220 "deg": 1,
221 "speed": 1
222 }
223 }
224```
225
226
227### <a name="mockcontrollers"></a>Implementing mock mode controllers
228
229By default, mock mode returns programmed responses, like "Sample text" for a string, a number for an integer, and so on.
230
231But you can also create mock controllers with handler methods that return custom responses.
232
233Place these custom "mock" controllers in the `/api/mock` directory.
234
235Here's an example that returns some data whenever the `search()` handler method is called:
236
237
238```javascript
239 'use strict';
240
241 module.exports = {
242 search: search
243 };
244
245 function search(req, res, next) {
246
247 res.json([{ user: 'mock', created: new Date(), text: 'this'}]);
248 }
249```
250
251###<a name="wireup"></a>Wiring up and implementing the API controller
252
253After you're happy with your API design, you're ready to implement wire up the controller for the `/weather` path.
254
255You simply specify in the Swagger spec the route handler (controller) file, which method to call in the controller (operationId), and any query parameters you wish to pass:
256
257In weather sample's `swagger.yaml` file, it looks like this:
258
259```yaml
260 paths:
261 /weather:
262 x-swagger-router-controller: weather
263 get:
264 description: "Returns current weather in the specified city to the caller"
265 operationId: getWeatherByCity
266 parameters:
267 - name: city
268 in: query
269 description: "The city you want weather for in the form city,state,country"
270 required: true
271 type: "string"
272```
273
274Finally, implement the route's operation -- the getWeatherByCity() method in `api/controllers/weather.js` -- which calls the back-end service and returns the response.
275
276Here is the sample controller implementation for a weather API:
277
278```javascript
279'use strict';
280
281var util = require('util');
282var request = require('request');
283
284module.exports = {
285 getWeatherByCity: getWeatherByCity
286}
287
288function getWeatherByCity(req, res) {
289 var city = req.swagger.params.city.value;
290 var url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&units=imperial";
291 console.log('Executing request: '+url);
292 request.get(url).pipe(res);
293 };
294```
295
296In the case of this sample weather API, the controller calls the back-end service (the [OpenWeatherMap](http://openweathermap.org/) API). When you call the API like this:
297
298`curl http://localhost:10010/weather?city=Boulder,CO`
299
300The same response object that you previously modeled and tested in mock mode is filled in with the correct values:
301
302
303```json
304 {
305 "base": "cmc stations",
306 "clouds": {
307 "all": 40
308 },
309 "cod": 200,
310 "coord": {
311 "lat": 40.02,
312 "lon": -105.28
313 },
314 "dt": 1411077635,
315 "id": 5574991,
316 "main": {
317 "humidity": 27,
318 "pressure": 1016,
319 "temp": 87.62,
320 "temp_max": 91.99,
321 "temp_min": 80.01
322 },
323 "name": "",
324 "sys": {
325 "country": "United States of America",
326 "id": 538,
327 "message": 0.0175,
328 "sunrise": 1411044334,
329 "sunset": 1411088663,
330 "type": 1
331 },
332 "weather": [
333 {
334 "description": "scattered clouds",
335 "icon": "03d",
336 "id": 802,
337 "main": "Clouds"
338 }
339 ],
340 "wind": {
341 "deg": 160,
342 "speed": 7.78
343 }
344 }
345```
346
347
348