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

What's hot

Backend Programming
Backend ProgrammingBackend Programming
Backend Programming
Ruwandi Madhunamali
 
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Edureka!
 
SHACL by example
SHACL by exampleSHACL by example
SHACL by example
Jose Emilio Labra Gayo
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
Ahmad Fatoni
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
Omri Spector
 
Expository essay
Expository essayExpository essay
Expository essay
Robbie Jean Alvarado
 
Kinds of sentences
Kinds of sentencesKinds of sentences
Kinds of sentences
'Maryjoy Elyneth Duguran
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback Commands
Michael Miles
 
Figurative Devices
Figurative DevicesFigurative Devices
Figurative Devices
Anindita Banerjee
 
Variable hoisting in JavaScript
Variable hoisting in JavaScriptVariable hoisting in JavaScript
Variable hoisting in JavaScript
Ideas2IT Technologies
 
How to use a dictionary
How to use a dictionaryHow to use a dictionary
How to use a dictionary
Bob Bob
 
Dive into Catalyst
Dive into CatalystDive into Catalyst
Dive into Catalyst
Cheng Lian
 
Narrative Writing PPT
Narrative Writing PPTNarrative Writing PPT
Narrative Writing PPT
Rahul Jose
 
Progressive Tenses of Verbs
Progressive Tenses of VerbsProgressive Tenses of Verbs
Progressive Tenses of Verbs
'Maryjoy Elyneth Duguran
 
Main Ideas and Supporting Details for Second Graders
Main Ideas and Supporting Details for Second GradersMain Ideas and Supporting Details for Second Graders
Main Ideas and Supporting Details for Second Gradersgherm6
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
Simplilearn
 
Writing Process grade 1
Writing Process grade 1Writing Process grade 1
Writing Process grade 1
Shaa Sarah
 
Adjective complement
Adjective complementAdjective complement
Adjective complement
Nicolai Bautista
 

What's hot (20)

Backend Programming
Backend ProgrammingBackend Programming
Backend Programming
 
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
 
SHACL by example
SHACL by exampleSHACL by example
SHACL by example
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
Expository essay
Expository essayExpository essay
Expository essay
 
Kinds of sentences
Kinds of sentencesKinds of sentences
Kinds of sentences
 
React and redux
React and reduxReact and redux
React and redux
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback Commands
 
Figurative Devices
Figurative DevicesFigurative Devices
Figurative Devices
 
Variable hoisting in JavaScript
Variable hoisting in JavaScriptVariable hoisting in JavaScript
Variable hoisting in JavaScript
 
How to use a dictionary
How to use a dictionaryHow to use a dictionary
How to use a dictionary
 
Dive into Catalyst
Dive into CatalystDive into Catalyst
Dive into Catalyst
 
Narrative Writing PPT
Narrative Writing PPTNarrative Writing PPT
Narrative Writing PPT
 
Progressive Tenses of Verbs
Progressive Tenses of VerbsProgressive Tenses of Verbs
Progressive Tenses of Verbs
 
Main Ideas and Supporting Details for Second Graders
Main Ideas and Supporting Details for Second GradersMain Ideas and Supporting Details for Second Graders
Main Ideas and Supporting Details for Second Graders
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Impromptu Speech
Impromptu SpeechImpromptu Speech
Impromptu Speech
 
Writing Process grade 1
Writing Process grade 1Writing Process grade 1
Writing Process grade 1
 
Adjective complement
Adjective complementAdjective complement
Adjective complement
 

Similar to Mirage For Beginners

How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
Wim Selles
 
Rapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirageRapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirage
Krzysztof Bialek
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
Javier Abadía
 
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Roman Kirillov
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
Chris Tankersley
 
Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applications
Loiane Groner
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
Amazon Web Services
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
InnovationM
 
Retrofit Library In Android
Retrofit Library In AndroidRetrofit Library In Android
Retrofit Library In Android
InnovationM
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVCGuy Nir
 
Introduction to CloudStack API
Introduction to CloudStack APIIntroduction to CloudStack API
Introduction to CloudStack API
Krunal Jain
 
05.SharePointCSOM
05.SharePointCSOM05.SharePointCSOM
05.SharePointCSOMEaswariSP
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
Daniel Bryant
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Frost
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
Yakov Fain
 
Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8
wsmarouan
 

Similar to Mirage For Beginners (20)

How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018How React Native, Appium and me made each other shine @Frontmania 16-11-2018
How React Native, Appium and me made each other shine @Frontmania 16-11-2018
 
Rapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirageRapid prototyping and easy testing with ember cli mirage
Rapid prototyping and easy testing with ember cli mirage
 
Vue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMRVue.js + Django - configuración para desarrollo con webpack y HMR
Vue.js + Django - configuración para desarrollo con webpack y HMR
 
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
Serverless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applicationsServerless Angular, Material, Firebase and Google Cloud applications
Serverless Angular, Material, Firebase and Google Cloud applications
 
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
AWS re:Invent 2016: Chalice: A Serverless Microframework for Python (DEV308)
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
 
Retrofit Library In Android
Retrofit Library In AndroidRetrofit Library In Android
Retrofit Library In Android
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
Introduction to CloudStack API
Introduction to CloudStack APIIntroduction to CloudStack API
Introduction to CloudStack API
 
05.SharePointCSOM
05.SharePointCSOM05.SharePointCSOM
05.SharePointCSOM
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8Création d'application Ionic & Angular & Drupal 8
Création d'application Ionic & Angular & Drupal 8
 

More from Wilson Su

NestJS
NestJSNestJS
NestJS
Wilson Su
 
The Jira How-To Guide
The Jira How-To GuideThe Jira How-To Guide
The Jira How-To Guide
Wilson Su
 
The Future of Web Development
The Future of Web DevelopmentThe Future of Web Development
The Future of Web Development
Wilson Su
 
Web Usability
Web UsabilityWeb Usability
Web Usability
Wilson Su
 
Puppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node APIPuppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node API
Wilson Su
 
Practical JavaScript Programming - Session 8/8
Practical JavaScript Programming - Session 8/8Practical JavaScript Programming - Session 8/8
Practical JavaScript Programming - Session 8/8
Wilson Su
 
Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 7/8Practical JavaScript Programming - Session 7/8
Practical JavaScript Programming - Session 7/8
Wilson Su
 
Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8Practical JavaScript Programming - Session 6/8
Practical JavaScript Programming - Session 6/8
Wilson Su
 
Practical JavaScript Programming - Session 5/8
Practical JavaScript Programming - Session 5/8Practical JavaScript Programming - Session 5/8
Practical JavaScript Programming - Session 5/8
Wilson Su
 
Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8Practical JavaScript Programming - Session 4/8
Practical JavaScript Programming - Session 4/8
Wilson Su
 
Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8Practical JavaScript Programming - Session 3/8
Practical JavaScript Programming - Session 3/8
Wilson Su
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8
Wilson Su
 
Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8Practical JavaScript Programming - Session 1/8
Practical JavaScript Programming - Session 1/8
Wilson Su
 

More from Wilson Su (13)

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

Recently uploaded

DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 

Recently uploaded (20)

DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 

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