SlideShare a Scribd company logo
Mirage For Beginners
Mirage Version 0.1.41
Wilson Su
Agenda
Background
1
Mirage
Introduction
2
Code
Examples
3
2
Background
3
Given a web app that
accesses data in the server
through RESTful APIs
4
API Request and Response
HTTP Request
GET/POST/PUT/DELETE ...
HTTP Response
JSON Data
Client Server
Web App
API
Controller
Data
5
Front-end developers
want to implement web UIs
before the APIs are ready
6
Develop New Features
Client Server
Web App
API
Controller
Data
GET /api/products
404 Not Found
7
What’s The Next Step
Wait for the backend side to complete the API development
A
Do the API development yourself
B
Add mock data to the API request functions in the client side
C Add mock data to the API request functions in the client side
C
8
API Function Example
// The fake function
function fetchProducts() {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 1, name: 'Orange' },
{ id: 2, name: 'Banana' },
]);
}, 400);
});
}
// The actual function
function fetchProducts() {
return fetch('/api/products');
}
Must be changed to look like the right
one after the API is completed
9
You can start to use Mirage
10
Mirage Introduction
11
What’s Mirage
Mirage
− is an API mocking library running in the browser
− runs alongside the rest of your frontend JavaScript code
− uses an in-memory database to maintain the data
12
How Mirage Works?
Mirage intercepts requests
by stubbing native fetch and
XMLHttpRequest
13
API Request and Response
HTTP Request
GET/POST/PUT/DELETE ...
HTTP Response
JSON Data
Client Server
Web App
API
Controller
Data
fetch
XMLHttpRequest
14
With Mirage Server In The Client
Client
Mock API Mock Data
Fake HTTP Response
GET /api/products
Web App
fetch
XMLHttpRequest
15
In-Memory DB
Override Native XMLHttpRequest
const nativeXMLHttpRequest = window.XMLHttpRequest;
const makeFakeRequest = () => {
function FakeRequest() {}
FakeRequest.prototype.send = () => { ... };
FakeRequest.prototype.abort = () => { ... };
...
return FakeRequest;
};
window.XMLHttpRequest = makeFakeRequest();
16
Code Examples
17
Create Mirage Server
import { createServer } from 'miragejs';
createServer({
routes() {
this.timing = 400; // The Server's response time in milliseconds
this.get('/api/products', () => {
return {
data: [{ id: 1, name: 'Orange' }, { id: 2, name: 'Banana' }],
};
});
},
});
18
Dynamic Handlers
import { createServer, Model } from 'miragejs';
createServer({
models: { product: Model },
routes() {
this.get('/api/products', schema => schema.products.all());
this.post('/api/products', (schema, request) => {
const body = JSON.parse(request.requestBody);
return schema.products.create(body);
});
},
});
19
Create Initial Data
20
createServer({
models: { product: Model },
seeds(server) {
server.create(
'product',
{ id: 1, name: 'Orange' },
);
},
});
createServer({
models: { product: Model },
seeds(server) {
server.db.loadData({
products: [
{ id: 1, name: 'Orange' },
],
});
},
});
Dynamic Segments
21
createServer({
models: { product: Model },
routes() {
this.get('/api/products/:id', (schema, request) => {
return schema.products.find(request.params.id);
});
this.delete('/api/products/:id', (schema, request) => {
return schema.products.find(request.params.id).destroy();
});
},
});
More Examples
22
Project Folder Structure
scripts
ㄴ app.js
mock
ㄴ routes
ㄴ product
ㄴ list.route.js
ㄴ detail.route.js
ㄴ server.js
ㄴ settings.dev.js
index.html
✓ Include configurations such as the
response time and enabled routes in
/mock/settings.dev.js
✓ Put route files under /mock/routes
✓ Add subfolders and route files for
different features
✓ No need to update /mock/server.js
when new routes added
23
/mock/settings.dev.js
export default {
delay: 400,
routes: [
'product/list', //=> /mock/routes/product/list.route.js
'product/detail', //=> /mock/routes/product/detail.route.js
],
};
24
/mock/server.js (1)
const context = require.context('./routes', true, /.route.js$/);
const routes = context
.keys()
.map(filepath => {
const name = filepath.match(/./([w/-]+).route.js/)[1];
const route = context(filepath).default;
return { name, route };
})
.filter(({ name }) => settings.routes.includes(name));
25
/mock/server.js (2)
export const makeServer = settings => {
createServer({
routes() {
this.timing = settings.delay;
routes.forEach(({ route }) => route.routes(this));
this.passthrough();
},
});
};
makeServer(settings);
26

More Related Content

PDF
OAuth2 and Spring Security
PPTX
Spring Security
PDF
Nestjs MasterClass Slides
PPT
Presentation Spring
PPTX
Spring Security 5
PPTX
Concurrency in Java
PDF
BugBounty Roadmap with Mohammed Adam
PPTX
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
OAuth2 and Spring Security
Spring Security
Nestjs MasterClass Slides
Presentation Spring
Spring Security 5
Concurrency in Java
BugBounty Roadmap with Mohammed Adam
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour

What's hot (20)

PDF
Mocking APIs Collaboratively with Postman
PPTX
Introduction to Spring Framework
PDF
ES2015 / ES6: Basics of modern Javascript
PDF
Intro to Asynchronous Javascript
PPTX
Pentesting ReST API
PDF
AWS EMR Cost optimization
PDF
RESTful API in Node.pdf
PDF
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
PDF
Introduction to MariaDB
PDF
Getting Started with Apache Spark on Kubernetes
PPTX
Solr Exchange: Introduction to SolrCloud
PPTX
Apache Flink Training: DataStream API Part 1 Basic
PDF
Java 8 Lambda Expressions & Streams
PPTX
How Hashmap works internally in java
PPTX
Yahoo compares Storm and Spark
PDF
20141223 머하웃(mahout) 협업필터링_추천시스템구현
PDF
3. Java Script
PDF
Web Development with Python and Django
PDF
Spring Data JPA
PDF
Spring MVC Framework
Mocking APIs Collaboratively with Postman
Introduction to Spring Framework
ES2015 / ES6: Basics of modern Javascript
Intro to Asynchronous Javascript
Pentesting ReST API
AWS EMR Cost optimization
RESTful API in Node.pdf
Garage4Hackers Ranchoddas Webcast Series - Bypassing Modern WAF's Exemplified...
Introduction to MariaDB
Getting Started with Apache Spark on Kubernetes
Solr Exchange: Introduction to SolrCloud
Apache Flink Training: DataStream API Part 1 Basic
Java 8 Lambda Expressions & Streams
How Hashmap works internally in java
Yahoo compares Storm and Spark
20141223 머하웃(mahout) 협업필터링_추천시스템구현
3. Java Script
Web Development with Python and Django
Spring Data JPA
Spring MVC Framework
Ad

Similar to Mirage For Beginners (20)

PDF
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
PPTX
Rapid prototyping and easy testing with ember cli mirage
PPTX
Vue.js + Django - configuración para desarrollo con webpack y HMR
PDF
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
PDF
using Mithril.js + postgREST to build and consume API's
PDF
Complex Sites with Silex
PDF
Serverless Angular, Material, Firebase and Google Cloud applications
PDF
Retrofit Library In Android
PDF
Retrofit library for android
PPT
Spring 3.x - Spring MVC
PDF
Introduction to CloudStack API
PPTX
05.SharePointCSOM
PDF
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
PPT
Intoduction to Play Framework
PPTX
Django + Vue, JavaScript de 3ª generación para modernizar Django
PPTX
Tamir Dresher - What’s new in ASP.NET Core 6
PDF
Angular 4 for Java Developers
PDF
Création d'application Ionic & Angular & Drupal 8
ODP
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
PDF
Technozaure - Angular2
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Rapid prototyping and easy testing with ember cli mirage
Vue.js + Django - configuración para desarrollo con webpack y HMR
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
using Mithril.js + postgREST to build and consume API's
Complex Sites with Silex
Serverless Angular, Material, Firebase and Google Cloud applications
Retrofit Library In Android
Retrofit library for android
Spring 3.x - Spring MVC
Introduction to CloudStack API
05.SharePointCSOM
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
Intoduction to Play Framework
Django + Vue, JavaScript de 3ª generación para modernizar Django
Tamir Dresher - What’s new in ASP.NET Core 6
Angular 4 for Java Developers
Création d'application Ionic & Angular & Drupal 8
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Technozaure - Angular2
Ad

More from Wilson Su (13)

PDF
NestJS
PDF
The Jira How-To Guide
PDF
The Future of Web Development
PDF
Web Usability
PDF
Puppeteer - Headless Chrome Node API
PDF
Practical JavaScript Programming - Session 8/8
PDF
Practical JavaScript Programming - Session 7/8
PDF
Practical JavaScript Programming - Session 6/8
PDF
Practical JavaScript Programming - Session 5/8
PDF
Practical JavaScript Programming - Session 4/8
PDF
Practical JavaScript Programming - Session 3/8
PDF
Practical JavaScript Programming - Session 2/8
PDF
Practical JavaScript Programming - Session 1/8
NestJS
The Jira How-To Guide
The Future of Web Development
Web Usability
Puppeteer - Headless Chrome Node API
Practical JavaScript Programming - Session 8/8
Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 5/8
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 1/8

Recently uploaded (20)

PDF
737-MAX_SRG.pdf student reference guides
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PPTX
Sustainable Sites - Green Building Construction
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Well-logging-methods_new................
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Current and future trends in Computer Vision.pptx
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
PPT on Performance Review to get promotions
PPTX
Artificial Intelligence
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Construction Project Organization Group 2.pptx
737-MAX_SRG.pdf student reference guides
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
Sustainable Sites - Green Building Construction
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Foundation to blockchain - A guide to Blockchain Tech
III.4.1.2_The_Space_Environment.p pdffdf
additive manufacturing of ss316l using mig welding
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Well-logging-methods_new................
R24 SURVEYING LAB MANUAL for civil enggi
Current and future trends in Computer Vision.pptx
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
Embodied AI: Ushering in the Next Era of Intelligent Systems
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT on Performance Review to get promotions
Artificial Intelligence
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Construction Project Organization Group 2.pptx

Mirage For Beginners

  • 1. Mirage For Beginners Mirage Version 0.1.41 Wilson Su
  • 4. Given a web app that accesses data in the server through RESTful APIs 4
  • 5. API Request and Response HTTP Request GET/POST/PUT/DELETE ... HTTP Response JSON Data Client Server Web App API Controller Data 5
  • 6. Front-end developers want to implement web UIs before the APIs are ready 6
  • 7. Develop New Features Client Server Web App API Controller Data GET /api/products 404 Not Found 7
  • 8. What’s The Next Step Wait for the backend side to complete the API development A Do the API development yourself B Add mock data to the API request functions in the client side C Add mock data to the API request functions in the client side C 8
  • 9. API Function Example // The fake function function fetchProducts() { return new Promise((resolve) => { setTimeout(() => { resolve([ { id: 1, name: 'Orange' }, { id: 2, name: 'Banana' }, ]); }, 400); }); } // The actual function function fetchProducts() { return fetch('/api/products'); } Must be changed to look like the right one after the API is completed 9
  • 10. You can start to use Mirage 10
  • 12. What’s Mirage Mirage − is an API mocking library running in the browser − runs alongside the rest of your frontend JavaScript code − uses an in-memory database to maintain the data 12
  • 13. How Mirage Works? Mirage intercepts requests by stubbing native fetch and XMLHttpRequest 13
  • 14. API Request and Response HTTP Request GET/POST/PUT/DELETE ... HTTP Response JSON Data Client Server Web App API Controller Data fetch XMLHttpRequest 14
  • 15. With Mirage Server In The Client Client Mock API Mock Data Fake HTTP Response GET /api/products Web App fetch XMLHttpRequest 15 In-Memory DB
  • 16. Override Native XMLHttpRequest const nativeXMLHttpRequest = window.XMLHttpRequest; const makeFakeRequest = () => { function FakeRequest() {} FakeRequest.prototype.send = () => { ... }; FakeRequest.prototype.abort = () => { ... }; ... return FakeRequest; }; window.XMLHttpRequest = makeFakeRequest(); 16
  • 18. Create Mirage Server import { createServer } from 'miragejs'; createServer({ routes() { this.timing = 400; // The Server's response time in milliseconds this.get('/api/products', () => { return { data: [{ id: 1, name: 'Orange' }, { id: 2, name: 'Banana' }], }; }); }, }); 18
  • 19. Dynamic Handlers import { createServer, Model } from 'miragejs'; createServer({ models: { product: Model }, routes() { this.get('/api/products', schema => schema.products.all()); this.post('/api/products', (schema, request) => { const body = JSON.parse(request.requestBody); return schema.products.create(body); }); }, }); 19
  • 20. Create Initial Data 20 createServer({ models: { product: Model }, seeds(server) { server.create( 'product', { id: 1, name: 'Orange' }, ); }, }); createServer({ models: { product: Model }, seeds(server) { server.db.loadData({ products: [ { id: 1, name: 'Orange' }, ], }); }, });
  • 21. Dynamic Segments 21 createServer({ models: { product: Model }, routes() { this.get('/api/products/:id', (schema, request) => { return schema.products.find(request.params.id); }); this.delete('/api/products/:id', (schema, request) => { return schema.products.find(request.params.id).destroy(); }); }, });
  • 23. Project Folder Structure scripts ㄴ app.js mock ㄴ routes ㄴ product ㄴ list.route.js ㄴ detail.route.js ㄴ server.js ㄴ settings.dev.js index.html ✓ Include configurations such as the response time and enabled routes in /mock/settings.dev.js ✓ Put route files under /mock/routes ✓ Add subfolders and route files for different features ✓ No need to update /mock/server.js when new routes added 23
  • 24. /mock/settings.dev.js export default { delay: 400, routes: [ 'product/list', //=> /mock/routes/product/list.route.js 'product/detail', //=> /mock/routes/product/detail.route.js ], }; 24
  • 25. /mock/server.js (1) const context = require.context('./routes', true, /.route.js$/); const routes = context .keys() .map(filepath => { const name = filepath.match(/./([w/-]+).route.js/)[1]; const route = context(filepath).default; return { name, route }; }) .filter(({ name }) => settings.routes.includes(name)); 25
  • 26. /mock/server.js (2) export const makeServer = settings => { createServer({ routes() { this.timing = settings.delay; routes.forEach(({ route }) => route.routes(this)); this.passthrough(); }, }); }; makeServer(settings); 26