Skip to content

Instantly share code, notes, and snippets.

@dontpaniclabsgists
Last active November 13, 2023 21:51
Show Gist options
  • Save dontpaniclabsgists/8ece5cb0e9cc7d587a294b11d0b99d00 to your computer and use it in GitHub Desktop.
Save dontpaniclabsgists/8ece5cb0e9cc7d587a294b11d0b99d00 to your computer and use it in GitHub Desktop.
Using JSON Server with Angular application configurations
// This is a partial example of the angular.json to show the new mock section under serve
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "json-server-demo:build:production"
},
"development": {
"buildTarget": "json-server-demo:build:development"
},
"mock": {
"buildTarget": "json-server-demo:build:development",
"proxyConfig": "./mocks/proxy.config.json"
}
},
"defaultConfiguration": "development"
},
{
"dateResponse": "2000-01-01",
"arrayResponse": [1, 2, 3, 4],
"saveResponse": {
"success": true
},
"textsDetails": [
{
"id": 1,
"texts": "first"
},
{
"id": 2,
"text": "second"
}
]
}
module.exports = (req, res, next) => {
if (req.method === 'POST') {
req.method = 'GET';
}
if (req.url === '/api/demo/special') {
res.json(generateResponse());
return;
}
next();
};
function generateResponse() {
const daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let weeks = [];
let days = [];
for (let i = 0; i < 7; i++) {
const dayOfWeek = daysOfWeek[i];
days.push({title: dayOfWeek});
}
for (let i = 1; i <= 52; i++) {
weeks.push({title: `Week ${i}`, days});
}
return {
weeks
};
}
// add this to the scripts section to make running JSON Server easy
"start:json-server": "json-server --watch mocks/db.json --routes mocks/routes.json --middlewares mocks/middleware.js"
{
"/api": {
"target": "http://localhost:3000"
}
}
{
"/api/demo/date": "/dateResponse",
"/api/demo/array": "/arrayResponse",
"/api/demo/save": "/saveResponse",
"/api/demo/texts/:id": "/textsDetails/:id"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment