json-server 0.12.2 → 0.14.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.babelrc +8 -6
- package/.eslintrc.js +2 -2
- package/CHANGELOG.md +18 -0
- package/README.md +26 -21
- package/{lib/server/public → dist}/favicon.ico +0 -0
- package/{lib/server/public → dist}/index.html +3 -11
- package/dist/main.css +675 -0
- package/dist/main.js +1 -0
- package/lib/cli/bin.js +4 -1
- package/lib/cli/index.js +13 -8
- package/lib/cli/run.js +98 -109
- package/lib/cli/utils/is.js +3 -4
- package/lib/cli/utils/load.js +71 -38
- package/lib/front/index.js +67 -0
- package/lib/server/body-parser.js +8 -3
- package/lib/server/defaults.js +44 -37
- package/lib/server/index.js +3 -5
- package/lib/server/mixins.js +37 -26
- package/lib/server/rewriter.js +7 -9
- package/lib/server/router/delay.js +4 -3
- package/lib/server/router/get-full-url.js +3 -4
- package/lib/server/router/index.js +59 -59
- package/lib/server/router/nested.js +13 -12
- package/lib/server/router/plural.js +134 -110
- package/lib/server/router/singular.js +35 -17
- package/lib/server/router/validate-data.js +4 -4
- package/lib/server/router/write.js +1 -1
- package/lib/server/utils.js +1 -1
- package/package.json +79 -51
- package/webpack.config.js +21 -0
- package/bin/index.js +0 -3
- package/lib/cli/example.json +0 -9
- package/lib/server/public/images/json.png +0 -0
- package/lib/server/public/main.js +0 -39
- package/lib/server/public/style.css +0 -73
package/dist/main.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
!function(t){var r={};function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}e.m=t,e.c=r,e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{enumerable:!0,get:n})},e.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},e.t=function(t,r){if(1&r&&(t=e(t)),8&r)return t;if(4&r&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(e.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&r&&"string"!=typeof t)for(var o in t)e.d(n,o,function(r){return t[r]}.bind(null,o));return n},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,r){return Object.prototype.hasOwnProperty.call(t,r)},e.p="",e(e.s=9)}([function(t,r,e){"use strict";r.a=function(t){var r=this.constructor;return this.then(function(e){return r.resolve(t()).then(function(){return e})},function(e){return r.resolve(t()).then(function(){return r.reject(e)})})}},function(t,r){var e;e=function(){return this}();try{e=e||new Function("return this")()}catch(t){"object"==typeof window&&(e=window)}t.exports=e},function(t,r,e){"use strict";(function(t){var n=e(0),o=setTimeout;function i(){}function s(t){if(!(this instanceof s))throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],h(t,this)}function c(t,r){for(;3===t._state;)t=t._value;0!==t._state?(t._handled=!0,s._immediateFn(function(){var e=1===t._state?r.onFulfilled:r.onRejected;if(null!==e){var n;try{n=e(t._value)}catch(t){return void a(r.promise,t)}f(r.promise,n)}else(1===t._state?f:a)(r.promise,t._value)})):t._deferreds.push(r)}function f(t,r){try{if(r===t)throw new TypeError("A promise cannot be resolved with itself.");if(r&&("object"==typeof r||"function"==typeof r)){var e=r.then;if(r instanceof s)return t._state=3,t._value=r,void u(t);if("function"==typeof e)return void h((n=e,o=r,function(){n.apply(o,arguments)}),t)}t._state=1,t._value=r,u(t)}catch(r){a(t,r)}var n,o}function a(t,r){t._state=2,t._value=r,u(t)}function u(t){2===t._state&&0===t._deferreds.length&&s._immediateFn(function(){t._handled||s._unhandledRejectionFn(t._value)});for(var r=0,e=t._deferreds.length;r<e;r++)c(t,t._deferreds[r]);t._deferreds=null}function l(t,r,e){this.onFulfilled="function"==typeof t?t:null,this.onRejected="function"==typeof r?r:null,this.promise=e}function h(t,r){var e=!1;try{t(function(t){e||(e=!0,f(r,t))},function(t){e||(e=!0,a(r,t))})}catch(t){if(e)return;e=!0,a(r,t)}}s.prototype.catch=function(t){return this.then(null,t)},s.prototype.then=function(t,r){var e=new this.constructor(i);return c(this,new l(t,r,e)),e},s.prototype.finally=n.a,s.all=function(t){return new s(function(r,e){if(!t||void 0===t.length)throw new TypeError("Promise.all accepts an array");var n=Array.prototype.slice.call(t);if(0===n.length)return r([]);var o=n.length;function i(t,s){try{if(s&&("object"==typeof s||"function"==typeof s)){var c=s.then;if("function"==typeof c)return void c.call(s,function(r){i(t,r)},e)}n[t]=s,0==--o&&r(n)}catch(t){e(t)}}for(var s=0;s<n.length;s++)i(s,n[s])})},s.resolve=function(t){return t&&"object"==typeof t&&t.constructor===s?t:new s(function(r){r(t)})},s.reject=function(t){return new s(function(r,e){e(t)})},s.race=function(t){return new s(function(r,e){for(var n=0,o=t.length;n<o;n++)t[n].then(r,e)})},s._immediateFn="function"==typeof t&&function(r){t(r)}||function(t){o(t,0)},s._unhandledRejectionFn=function(t){"undefined"!=typeof console&&console&&console.warn("Possible Unhandled Promise Rejection:",t)},r.a=s}).call(this,e(4).setImmediate)},function(t,r,e){"use strict";(function(t){var r=e(2),n=e(0),o=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==t)return t;throw new Error("unable to locate global object")}();"Promise"in o?o.Promise.prototype.finally||(o.Promise.prototype.finally=n.a):o.Promise=r.a}).call(this,e(1))},function(t,r,e){(function(t){var n=void 0!==t&&t||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;function i(t,r){this._id=t,this._clearFn=r}r.setTimeout=function(){return new i(o.call(setTimeout,n,arguments),clearTimeout)},r.setInterval=function(){return new i(o.call(setInterval,n,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(t){t&&t.close()},i.prototype.unref=i.prototype.ref=function(){},i.prototype.close=function(){this._clearFn.call(n,this._id)},r.enroll=function(t,r){clearTimeout(t._idleTimeoutId),t._idleTimeout=r},r.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},r._unrefActive=r.active=function(t){clearTimeout(t._idleTimeoutId);var r=t._idleTimeout;r>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},r))},e(5),r.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,r.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(this,e(1))},function(t,r,e){(function(t,r){!function(t,e){"use strict";if(!t.setImmediate){var n,o,i,s,c,f=1,a={},u=!1,l=t.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(t);h=h&&h.setTimeout?h:t,"[object process]"==={}.toString.call(t.process)?n=function(t){r.nextTick(function(){d(t)})}:!function(){if(t.postMessage&&!t.importScripts){var r=!0,e=t.onmessage;return t.onmessage=function(){r=!1},t.postMessage("","*"),t.onmessage=e,r}}()?t.MessageChannel?((i=new MessageChannel).port1.onmessage=function(t){d(t.data)},n=function(t){i.port2.postMessage(t)}):l&&"onreadystatechange"in l.createElement("script")?(o=l.documentElement,n=function(t){var r=l.createElement("script");r.onreadystatechange=function(){d(t),r.onreadystatechange=null,o.removeChild(r),r=null},o.appendChild(r)}):n=function(t){setTimeout(d,0,t)}:(s="setImmediate$"+Math.random()+"$",c=function(r){r.source===t&&"string"==typeof r.data&&0===r.data.indexOf(s)&&d(+r.data.slice(s.length))},t.addEventListener?t.addEventListener("message",c,!1):t.attachEvent("onmessage",c),n=function(r){t.postMessage(s+r,"*")}),h.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var r=new Array(arguments.length-1),e=0;e<r.length;e++)r[e]=arguments[e+1];var o={callback:t,args:r};return a[f]=o,n(f),f++},h.clearImmediate=p}function p(t){delete a[t]}function d(t){if(u)setTimeout(d,0,t);else{var r=a[t];if(r){u=!0;try{!function(t){var r=t.callback,n=t.args;switch(n.length){case 0:r();break;case 1:r(n[0]);break;case 2:r(n[0],n[1]);break;case 3:r(n[0],n[1],n[2]);break;default:r.apply(e,n)}}(r)}finally{p(t),u=!1}}}}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,e(1),e(6))},function(t,r){var e,n,o=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function c(t){if(e===setTimeout)return setTimeout(t,0);if((e===i||!e)&&setTimeout)return e=setTimeout,setTimeout(t,0);try{return e(t,0)}catch(r){try{return e.call(null,t,0)}catch(r){return e.call(this,t,0)}}}!function(){try{e="function"==typeof setTimeout?setTimeout:i}catch(t){e=i}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(t){n=s}}();var f,a=[],u=!1,l=-1;function h(){u&&f&&(u=!1,f.length?a=f.concat(a):l=-1,a.length&&p())}function p(){if(!u){var t=c(h);u=!0;for(var r=a.length;r;){for(f=a,a=[];++l<r;)f&&f[l].run();l=-1,r=a.length}f=null,u=!1,function(t){if(n===clearTimeout)return clearTimeout(t);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(t);try{n(t)}catch(r){try{return n.call(null,t)}catch(r){return n.call(this,t)}}}(t)}}function d(t,r){this.fun=t,this.array=r}function y(){}o.nextTick=function(t){var r=new Array(arguments.length-1);if(arguments.length>1)for(var e=1;e<arguments.length;e++)r[e-1]=arguments[e];a.push(new d(t,r)),1!==a.length||u||c(p)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=y,o.addListener=y,o.once=y,o.off=y,o.removeListener=y,o.removeAllListeners=y,o.emit=y,o.prependListener=y,o.prependOnceListener=y,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,r,e){},function(t,r,e){},function(t,r,e){"use strict";e.r(r);e(3);var n={searchParams:"URLSearchParams"in self,iterable:"Symbol"in self&&"iterator"in Symbol,blob:"FileReader"in self&&"Blob"in self&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in self,arrayBuffer:"ArrayBuffer"in self};if(n.arrayBuffer)var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],i=ArrayBuffer.isView||function(t){return t&&o.indexOf(Object.prototype.toString.call(t))>-1};function s(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function c(t){return"string"!=typeof t&&(t=String(t)),t}function f(t){var r={next:function(){var r=t.shift();return{done:void 0===r,value:r}}};return n.iterable&&(r[Symbol.iterator]=function(){return r}),r}function a(t){this.map={},t instanceof a?t.forEach(function(t,r){this.append(r,t)},this):Array.isArray(t)?t.forEach(function(t){this.append(t[0],t[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(r){this.append(r,t[r])},this)}function u(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function l(t){return new Promise(function(r,e){t.onload=function(){r(t.result)},t.onerror=function(){e(t.error)}})}function h(t){var r=new FileReader,e=l(r);return r.readAsArrayBuffer(t),e}function p(t){if(t.slice)return t.slice(0);var r=new Uint8Array(t.byteLength);return r.set(new Uint8Array(t)),r.buffer}function d(){return this.bodyUsed=!1,this._initBody=function(t){var r;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:n.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:n.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:n.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():n.arrayBuffer&&n.blob&&((r=t)&&DataView.prototype.isPrototypeOf(r))?(this._bodyArrayBuffer=p(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):n.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||i(t))?this._bodyArrayBuffer=p(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},n.blob&&(this.blob=function(){var t=u(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?u(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(h)}),this.text=function(){var t,r,e,n=u(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,r=new FileReader,e=l(r),r.readAsText(t),e;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var r=new Uint8Array(t),e=new Array(r.length),n=0;n<r.length;n++)e[n]=String.fromCharCode(r[n]);return e.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},n.formData&&(this.formData=function(){return this.text().then(_)}),this.json=function(){return this.text().then(JSON.parse)},this}a.prototype.append=function(t,r){t=s(t),r=c(r);var e=this.map[t];this.map[t]=e?e+", "+r:r},a.prototype.delete=function(t){delete this.map[s(t)]},a.prototype.get=function(t){return t=s(t),this.has(t)?this.map[t]:null},a.prototype.has=function(t){return this.map.hasOwnProperty(s(t))},a.prototype.set=function(t,r){this.map[s(t)]=c(r)},a.prototype.forEach=function(t,r){for(var e in this.map)this.map.hasOwnProperty(e)&&t.call(r,this.map[e],e,this)},a.prototype.keys=function(){var t=[];return this.forEach(function(r,e){t.push(e)}),f(t)},a.prototype.values=function(){var t=[];return this.forEach(function(r){t.push(r)}),f(t)},a.prototype.entries=function(){var t=[];return this.forEach(function(r,e){t.push([e,r])}),f(t)},n.iterable&&(a.prototype[Symbol.iterator]=a.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function b(t,r){var e,n,o=(r=r||{}).body;if(t instanceof b){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,r.headers||(this.headers=new a(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=r.credentials||this.credentials||"same-origin",!r.headers&&this.headers||(this.headers=new a(r.headers)),this.method=(e=r.method||this.method||"GET",n=e.toUpperCase(),y.indexOf(n)>-1?n:e),this.mode=r.mode||this.mode||null,this.signal=r.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function _(t){var r=new FormData;return t.trim().split("&").forEach(function(t){if(t){var e=t.split("="),n=e.shift().replace(/\+/g," "),o=e.join("=").replace(/\+/g," ");r.append(decodeURIComponent(n),decodeURIComponent(o))}}),r}function w(t,r){r||(r={}),this.type="default",this.status=void 0===r.status?200:r.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in r?r.statusText:"OK",this.headers=new a(r.headers),this.url=r.url||"",this._initBody(t)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},d.call(b.prototype),d.call(w.prototype),w.prototype.clone=function(){return new w(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new a(this.headers),url:this.url})},w.error=function(){var t=new w(null,{status:0,statusText:""});return t.type="error",t};var m=[301,302,303,307,308];w.redirect=function(t,r){if(-1===m.indexOf(r))throw new RangeError("Invalid status code");return new w(null,{status:r,headers:{location:t}})};var g=self.DOMException;try{new g}catch(t){(g=function(t,r){this.message=t,this.name=r;var e=Error(t);this.stack=e.stack}).prototype=Object.create(Error.prototype),g.prototype.constructor=g}function T(t,r){return new Promise(function(e,o){var i=new b(t,r);if(i.signal&&i.signal.aborted)return o(new g("Aborted","AbortError"));var s=new XMLHttpRequest;function c(){s.abort()}s.onload=function(){var t,r,n={status:s.status,statusText:s.statusText,headers:(t=s.getAllResponseHeaders()||"",r=new a,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(t){var e=t.split(":"),n=e.shift().trim();if(n){var o=e.join(":").trim();r.append(n,o)}}),r)};n.url="responseURL"in s?s.responseURL:n.headers.get("X-Request-URL");var o="response"in s?s.response:s.responseText;e(new w(o,n))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.onabort=function(){o(new g("Aborted","AbortError"))},s.open(i.method,i.url,!0),"include"===i.credentials?s.withCredentials=!0:"omit"===i.credentials&&(s.withCredentials=!1),"responseType"in s&&n.blob&&(s.responseType="blob"),i.headers.forEach(function(t,r){s.setRequestHeader(r,t)}),i.signal&&(i.signal.addEventListener("abort",c),s.onreadystatechange=function(){4===s.readyState&&i.signal.removeEventListener("abort",c)}),s.send(void 0===i._bodyInit?null:i._bodyInit)})}T.polyfill=!0,self.fetch||(self.fetch=T,self.Headers=a,self.Request=b,self.Response=w);var E=function(){},x={},v=[],B=[];function j(t,r){var e,n,o,i,s=B;for(i=arguments.length;i-- >2;)v.push(arguments[i]);for(r&&null!=r.children&&(v.length||v.push(r.children),delete r.children);v.length;)if((n=v.pop())&&void 0!==n.pop)for(i=n.length;i--;)v.push(n[i]);else"boolean"==typeof n&&(n=null),(o="function"!=typeof t)&&(null==n?n="":"number"==typeof n?n=String(n):"string"!=typeof n&&(o=!1)),o&&e?s[s.length-1]+=n:s===B?s=[n]:s.push(n),e=o;var c=new E;return c.nodeName=t,c.children=s,c.attributes=null==r?void 0:r,c.key=null==r?void 0:r.key,void 0!==x.vnode&&x.vnode(c),c}function A(t,r){for(var e in r)t[e]=r[e];return t}function U(t,r){null!=t&&("function"==typeof t?t(r):t.current=r)}var F="function"==typeof Promise?Promise.resolve().then.bind(Promise.resolve()):setTimeout;var R=/acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i,S=[];function O(t){!t._dirty&&(t._dirty=!0)&&1==S.push(t)&&(x.debounceRendering||F)(k)}function k(){for(var t;t=S.pop();)t._dirty&&Y(t)}function P(t,r){return t.normalizedNodeName===r||t.nodeName.toLowerCase()===r.toLowerCase()}function L(t){var r=A({},t.attributes);r.children=t.children;var e=t.nodeName.defaultProps;if(void 0!==e)for(var n in e)void 0===r[n]&&(r[n]=e[n]);return r}function D(t){var r=t.parentNode;r&&r.removeChild(t)}function I(t,r,e,n,o){if("className"===r&&(r="class"),"key"===r) ;else if("ref"===r)U(e,null),U(n,t);else if("class"!==r||o)if("style"===r){if(n&&"string"!=typeof n&&"string"!=typeof e||(t.style.cssText=n||""),n&&"object"==typeof n){if("string"!=typeof e)for(var i in e)i in n||(t.style[i]="");for(var i in n)t.style[i]="number"==typeof n[i]&&!1===R.test(i)?n[i]+"px":n[i]}}else if("dangerouslySetInnerHTML"===r)n&&(t.innerHTML=n.__html||"");else if("o"==r[0]&&"n"==r[1]){var s=r!==(r=r.replace(/Capture$/,""));r=r.toLowerCase().substring(2),n?e||t.addEventListener(r,M,s):t.removeEventListener(r,M,s),(t._listeners||(t._listeners={}))[r]=n}else if("list"!==r&&"type"!==r&&!o&&r in t){try{t[r]=null==n?"":n}catch(t){}null!=n&&!1!==n||"spellcheck"==r||t.removeAttribute(r)}else{var c=o&&r!==(r=r.replace(/^xlink:?/,""));null==n||!1===n?c?t.removeAttributeNS("http://www.w3.org/1999/xlink",r.toLowerCase()):t.removeAttribute(r):"function"!=typeof n&&(c?t.setAttributeNS("http://www.w3.org/1999/xlink",r.toLowerCase(),n):t.setAttribute(r,n))}else t.className=n||""}function M(t){return this._listeners[t.type](x.event&&x.event(t)||t)}var C=[],H=0,V=!1,W=!1;function q(){for(var t;t=C.shift();)x.afterMount&&x.afterMount(t),t.componentDidMount&&t.componentDidMount()}function G(t,r,e,n,o,i){H++||(V=null!=o&&void 0!==o.ownerSVGElement,W=null!=t&&!("__preactattr_"in t));var s=$(t,r,e,n,i);return o&&s.parentNode!==o&&o.appendChild(s),--H||(W=!1,i||q()),s}function $(t,r,e,n,o){var i=t,s=V;if(null!=r&&"boolean"!=typeof r||(r=""),"string"==typeof r||"number"==typeof r)return t&&void 0!==t.splitText&&t.parentNode&&(!t._component||o)?t.nodeValue!=r&&(t.nodeValue=r):(i=document.createTextNode(r),t&&(t.parentNode&&t.parentNode.replaceChild(i,t),z(t,!0))),i.__preactattr_=!0,i;var c,f,a=r.nodeName;if("function"==typeof a)return function(t,r,e,n){var o=t&&t._component,i=o,s=t,c=o&&t._componentConstructor===r.nodeName,f=c,a=L(r);for(;o&&!f&&(o=o._parentComponent);)f=o.constructor===r.nodeName;o&&f&&(!n||o._component)?(Q(o,a,3,e,n),t=o.base):(i&&!c&&(Z(i),t=s=null),o=J(r.nodeName,a,e),t&&!o.nextBase&&(o.nextBase=t,s=null),Q(o,a,1,e,n),t=o.base,s&&t!==s&&(s._component=null,z(s,!1)));return t}(t,r,e,n);if(V="svg"===a||"foreignObject"!==a&&V,a=String(a),(!t||!P(t,a))&&(c=a,(f=V?document.createElementNS("http://www.w3.org/2000/svg",c):document.createElement(c)).normalizedNodeName=c,i=f,t)){for(;t.firstChild;)i.appendChild(t.firstChild);t.parentNode&&t.parentNode.replaceChild(i,t),z(t,!0)}var u=i.firstChild,l=i.__preactattr_,h=r.children;if(null==l){l=i.__preactattr_={};for(var p=i.attributes,d=p.length;d--;)l[p[d].name]=p[d].value}return!W&&h&&1===h.length&&"string"==typeof h[0]&&null!=u&&void 0!==u.splitText&&null==u.nextSibling?u.nodeValue!=h[0]&&(u.nodeValue=h[0]):(h&&h.length||null!=u)&&function(t,r,e,n,o){var i,s,c,f,a,u=t.childNodes,l=[],h={},p=0,d=0,y=u.length,b=0,_=r?r.length:0;if(0!==y)for(var w=0;w<y;w++){var m=u[w],g=m.__preactattr_,T=_&&g?m._component?m._component.__key:g.key:null;null!=T?(p++,h[T]=m):(g||(void 0!==m.splitText?!o||m.nodeValue.trim():o))&&(l[b++]=m)}if(0!==_)for(var w=0;w<_;w++){f=r[w],a=null;var T=f.key;if(null!=T)p&&void 0!==h[T]&&(a=h[T],h[T]=void 0,p--);else if(d<b)for(i=d;i<b;i++)if(void 0!==l[i]&&(E=s=l[i],v=o,"string"==typeof(x=f)||"number"==typeof x?void 0!==E.splitText:"string"==typeof x.nodeName?!E._componentConstructor&&P(E,x.nodeName):v||E._componentConstructor===x.nodeName)){a=s,l[i]=void 0,i===b-1&&b--,i===d&&d++;break}a=$(a,f,e,n),c=u[w],a&&a!==t&&a!==c&&(null==c?t.appendChild(a):a===c.nextSibling?D(c):t.insertBefore(a,c))}var E,x,v;if(p)for(var w in h)void 0!==h[w]&&z(h[w],!1);for(;d<=b;)void 0!==(a=l[b--])&&z(a,!1)}(i,h,e,n,W||null!=l.dangerouslySetInnerHTML),function(t,r,e){var n;for(n in e)r&&null!=r[n]||null==e[n]||I(t,n,e[n],e[n]=void 0,V);for(n in r)"children"===n||"innerHTML"===n||n in e&&r[n]===("value"===n||"checked"===n?t[n]:e[n])||I(t,n,e[n],e[n]=r[n],V)}(i,r.attributes,l),V=s,i}function z(t,r){var e=t._component;e?Z(e):(null!=t.__preactattr_&&U(t.__preactattr_.ref,null),!1!==r&&null!=t.__preactattr_||D(t),N(t))}function N(t){for(t=t.lastChild;t;){var r=t.previousSibling;z(t,!0),t=r}}var X=[];function J(t,r,e){var n,o=X.length;for(t.prototype&&t.prototype.render?(n=new t(r,e),tt.call(n,r,e)):((n=new tt(r,e)).constructor=t,n.render=K);o--;)if(X[o].constructor===t)return n.nextBase=X[o].nextBase,X.splice(o,1),n;return n}function K(t,r,e){return this.constructor(t,e)}function Q(t,r,e,n,o){t._disable||(t._disable=!0,t.__ref=r.ref,t.__key=r.key,delete r.ref,delete r.key,void 0===t.constructor.getDerivedStateFromProps&&(!t.base||o?t.componentWillMount&&t.componentWillMount():t.componentWillReceiveProps&&t.componentWillReceiveProps(r,n)),n&&n!==t.context&&(t.prevContext||(t.prevContext=t.context),t.context=n),t.prevProps||(t.prevProps=t.props),t.props=r,t._disable=!1,0!==e&&(1!==e&&!1===x.syncComponentUpdates&&t.base?O(t):Y(t,1,o)),U(t.__ref,t))}function Y(t,r,e,n){if(!t._disable){var o,i,s,c=t.props,f=t.state,a=t.context,u=t.prevProps||c,l=t.prevState||f,h=t.prevContext||a,p=t.base,d=t.nextBase,y=p||d,b=t._component,_=!1,w=h;if(t.constructor.getDerivedStateFromProps&&(f=A(A({},f),t.constructor.getDerivedStateFromProps(c,f)),t.state=f),p&&(t.props=u,t.state=l,t.context=h,2!==r&&t.shouldComponentUpdate&&!1===t.shouldComponentUpdate(c,f,a)?_=!0:t.componentWillUpdate&&t.componentWillUpdate(c,f,a),t.props=c,t.state=f,t.context=a),t.prevProps=t.prevState=t.prevContext=t.nextBase=null,t._dirty=!1,!_){o=t.render(c,f,a),t.getChildContext&&(a=A(A({},a),t.getChildContext())),p&&t.getSnapshotBeforeUpdate&&(w=t.getSnapshotBeforeUpdate(u,l));var m,g,T=o&&o.nodeName;if("function"==typeof T){var E=L(o);(i=b)&&i.constructor===T&&E.key==i.__key?Q(i,E,1,a,!1):(m=i,t._component=i=J(T,E,a),i.nextBase=i.nextBase||d,i._parentComponent=t,Q(i,E,0,a,!1),Y(i,1,e,!0)),g=i.base}else s=y,(m=b)&&(s=t._component=null),(y||1===r)&&(s&&(s._component=null),g=G(s,o,a,e||!p,y&&y.parentNode,!0));if(y&&g!==y&&i!==b){var v=y.parentNode;v&&g!==v&&(v.replaceChild(g,y),m||(y._component=null,z(y,!1)))}if(m&&Z(m),t.base=g,g&&!n){for(var B=t,j=t;j=j._parentComponent;)(B=j).base=g;g._component=B,g._componentConstructor=B.constructor}}for(!p||e?C.push(t):_||(t.componentDidUpdate&&t.componentDidUpdate(u,l,w),x.afterUpdate&&x.afterUpdate(t));t._renderCallbacks.length;)t._renderCallbacks.pop().call(t);H||n||q()}}function Z(t){x.beforeUnmount&&x.beforeUnmount(t);var r=t.base;t._disable=!0,t.componentWillUnmount&&t.componentWillUnmount(),t.base=null;var e=t._component;e?Z(e):r&&(null!=r.__preactattr_&&U(r.__preactattr_.ref,null),t.nextBase=r,D(r),X.push(t),N(r)),U(t.__ref,null)}function tt(t,r){this._dirty=!0,this.context=r,this.props=t,this.state=this.state||{},this._renderCallbacks=[]}function rt(t,r,e){return G(e,t,{},!1,r,!1)}A(tt.prototype,{setState:function(t,r){this.prevState||(this.prevState=this.state),this.state=A(A({},this.state),"function"==typeof t?t(this.state,this.props):t),r&&this._renderCallbacks.push(r),O(this)},forceUpdate:function(t){t&&this._renderCallbacks.push(t),Y(this,2)},render:function(){}});e(7),e(8);function et(t){var r=t.name,e=t.length;return j("li",null,j("a",{href:r},"/",r)," ",j("sup",null,e?"".concat(e,"x"):"object"))}function nt(t){var r=t.db;return j("ul",null,Object.keys(r).map(function(t){return j(et,{name:t,length:Array.isArray(r[t])&&r[t].length})}))}function ot(){return j("p",null,"No resources found")}function it(t){var r=t.db;return j("div",null,j("h4",null,"Resources"),Object.keys(r).length?j(nt,{db:r}):j(ot,null))}function st(t){var r=t.customRoutes,e=Object.keys(r);if(e.length)return j("div",null,j("h4",null,"Custom Routes"),j("table",null,e.map(function(t){return j("tr",null,j("td",null,t),j("td",null,"⇢ ",r[t]))})))}window.fetch("db").then(function(t){return t.json()}).then(function(t){return rt(j(it,{db:t}),document.getElementById("resources"))}),window.fetch("__rules").then(function(t){return t.json()}).then(function(t){rt(j(st,{customRoutes:t}),document.getElementById("custom-routes"))})}]);
|
package/lib/cli/bin.js
CHANGED
package/lib/cli/index.js
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
|
-
|
|
1
|
+
"use strict";
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
const updateNotifier = require('update-notifier');
|
|
4
|
+
|
|
5
|
+
const yargs = require('yargs');
|
|
6
|
+
|
|
7
|
+
const run = require('./run');
|
|
8
|
+
|
|
9
|
+
const pkg = require('../../package.json');
|
|
7
10
|
|
|
8
11
|
module.exports = function () {
|
|
9
|
-
updateNotifier({
|
|
12
|
+
updateNotifier({
|
|
13
|
+
pkg
|
|
14
|
+
}).notify();
|
|
10
15
|
|
|
11
|
-
|
|
16
|
+
const argv = yargs.config('config').usage('$0 [options] <source>').options({
|
|
12
17
|
port: {
|
|
13
18
|
alias: 'p',
|
|
14
19
|
description: 'Set port',
|
|
@@ -17,7 +22,7 @@ module.exports = function () {
|
|
|
17
22
|
host: {
|
|
18
23
|
alias: 'H',
|
|
19
24
|
description: 'Set host',
|
|
20
|
-
default: '
|
|
25
|
+
default: 'localhost'
|
|
21
26
|
},
|
|
22
27
|
watch: {
|
|
23
28
|
alias: 'w',
|
package/lib/cli/run.js
CHANGED
|
@@ -1,31 +1,38 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
var fs = require('fs');
|
|
4
|
-
var path = require('path');
|
|
5
|
-
var jph = require('json-parse-helpfulerror');
|
|
6
|
-
var _ = require('lodash');
|
|
7
|
-
var chalk = require('chalk');
|
|
8
|
-
var enableDestroy = require('server-destroy');
|
|
9
|
-
var pause = require('connect-pause');
|
|
10
|
-
var is = require('./utils/is');
|
|
11
|
-
var load = require('./utils/load');
|
|
12
|
-
var example = require('./example.json');
|
|
13
|
-
var jsonServer = require('../server');
|
|
1
|
+
"use strict";
|
|
14
2
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
|
|
5
|
+
const path = require('path');
|
|
6
|
+
|
|
7
|
+
const jph = require('json-parse-helpfulerror');
|
|
8
|
+
|
|
9
|
+
const _ = require('lodash');
|
|
10
|
+
|
|
11
|
+
const chalk = require('chalk');
|
|
12
|
+
|
|
13
|
+
const enableDestroy = require('server-destroy');
|
|
14
|
+
|
|
15
|
+
const pause = require('connect-pause');
|
|
19
16
|
|
|
17
|
+
const is = require('./utils/is');
|
|
18
|
+
|
|
19
|
+
const load = require('./utils/load');
|
|
20
|
+
|
|
21
|
+
const jsonServer = require('../server');
|
|
22
|
+
|
|
23
|
+
function prettyPrint(argv, object, rules) {
|
|
24
|
+
const root = `http://${argv.host}:${argv.port}`;
|
|
20
25
|
console.log();
|
|
21
26
|
console.log(chalk.bold(' Resources'));
|
|
22
|
-
|
|
27
|
+
|
|
28
|
+
for (let prop in object) {
|
|
23
29
|
console.log(` ${root}/${prop}`);
|
|
24
30
|
}
|
|
25
31
|
|
|
26
32
|
if (rules) {
|
|
27
33
|
console.log();
|
|
28
34
|
console.log(chalk.bold(' Other routes'));
|
|
35
|
+
|
|
29
36
|
for (var rule in rules) {
|
|
30
37
|
console.log(` ${rule} -> ${rules[rule]}`);
|
|
31
38
|
}
|
|
@@ -37,22 +44,13 @@ function prettyPrint(argv, object, rules) {
|
|
|
37
44
|
console.log();
|
|
38
45
|
}
|
|
39
46
|
|
|
40
|
-
function createApp(
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
try {
|
|
48
|
-
router = jsonServer.router(is.JSON(source) ? source : object, foreignKeySuffix ? { foreignKeySuffix } : undefined);
|
|
49
|
-
} catch (e) {
|
|
50
|
-
console.log();
|
|
51
|
-
console.error(chalk.red(e.message.replace(/^/gm, ' ')));
|
|
52
|
-
process.exit(1);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
var defaultsOpts = {
|
|
47
|
+
function createApp(db, routes, middlewares, argv) {
|
|
48
|
+
const app = jsonServer.create();
|
|
49
|
+
const foreignKeySuffix = argv.foreignKeySuffix;
|
|
50
|
+
let router = jsonServer.router(db, foreignKeySuffix ? {
|
|
51
|
+
foreignKeySuffix
|
|
52
|
+
} : undefined);
|
|
53
|
+
const defaultsOpts = {
|
|
56
54
|
logger: !argv.quiet,
|
|
57
55
|
readOnly: argv.readOnly,
|
|
58
56
|
noCors: argv.noCors,
|
|
@@ -64,11 +62,11 @@ function createApp(source, object, routes, middlewares, argv) {
|
|
|
64
62
|
defaultsOpts.static = path.join(process.cwd(), argv.static);
|
|
65
63
|
}
|
|
66
64
|
|
|
67
|
-
|
|
65
|
+
const defaults = jsonServer.defaults(defaultsOpts);
|
|
68
66
|
app.use(defaults);
|
|
69
67
|
|
|
70
68
|
if (routes) {
|
|
71
|
-
|
|
69
|
+
const rewriter = jsonServer.rewriter(routes);
|
|
72
70
|
app.use(rewriter);
|
|
73
71
|
}
|
|
74
72
|
|
|
@@ -83,23 +81,22 @@ function createApp(source, object, routes, middlewares, argv) {
|
|
|
83
81
|
router.db._.id = argv.id;
|
|
84
82
|
app.db = router.db;
|
|
85
83
|
app.use(router);
|
|
86
|
-
|
|
87
84
|
return app;
|
|
88
85
|
}
|
|
89
86
|
|
|
90
87
|
module.exports = function (argv) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
88
|
+
const source = argv._[0];
|
|
89
|
+
let app;
|
|
90
|
+
let server;
|
|
94
91
|
|
|
95
92
|
if (!fs.existsSync(argv.snapshots)) {
|
|
96
93
|
console.log(`Error: snapshots directory ${argv.snapshots} doesn't exist`);
|
|
97
94
|
process.exit(1);
|
|
98
|
-
}
|
|
95
|
+
} // noop log fn
|
|
96
|
+
|
|
99
97
|
|
|
100
|
-
// noop log fn
|
|
101
98
|
if (argv.quiet) {
|
|
102
|
-
console.log =
|
|
99
|
+
console.log = () => {};
|
|
103
100
|
}
|
|
104
101
|
|
|
105
102
|
console.log();
|
|
@@ -107,99 +104,89 @@ module.exports = function (argv) {
|
|
|
107
104
|
|
|
108
105
|
function start(cb) {
|
|
109
106
|
console.log();
|
|
110
|
-
|
|
111
|
-
// Be nice and create a default db.json if it doesn't exist
|
|
112
|
-
if (is.JSON(source) && !fs.existsSync(source)) {
|
|
113
|
-
console.log(chalk.yellow(` Oops, ${source} doesn't seem to exist`));
|
|
114
|
-
console.log(chalk.yellow(` Creating ${source} with some default data`));
|
|
115
|
-
console.log();
|
|
116
|
-
fs.writeFileSync(source, JSON.stringify(example, null, 2));
|
|
117
|
-
}
|
|
118
|
-
|
|
119
107
|
console.log(chalk.gray(' Loading', source));
|
|
108
|
+
server = undefined; // create db and load object, JSON file, JS or HTTP database
|
|
120
109
|
|
|
121
|
-
|
|
122
|
-
load(source, function (err, data) {
|
|
123
|
-
if (err) throw err;
|
|
124
|
-
|
|
110
|
+
return load(source).then(db => {
|
|
125
111
|
// Load additional routes
|
|
126
|
-
|
|
112
|
+
let routes;
|
|
113
|
+
|
|
127
114
|
if (argv.routes) {
|
|
128
115
|
console.log(chalk.gray(' Loading', argv.routes));
|
|
129
116
|
routes = JSON.parse(fs.readFileSync(argv.routes));
|
|
130
|
-
}
|
|
117
|
+
} // Load middlewares
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
let middlewares;
|
|
131
121
|
|
|
132
|
-
// Load middlewares
|
|
133
|
-
var middlewares = void 0;
|
|
134
122
|
if (argv.middlewares) {
|
|
135
123
|
middlewares = argv.middlewares.map(function (m) {
|
|
136
124
|
console.log(chalk.gray(' Loading', m));
|
|
137
125
|
return require(path.resolve(m));
|
|
138
126
|
});
|
|
139
|
-
}
|
|
127
|
+
} // Done
|
|
140
128
|
|
|
141
|
-
// Done
|
|
142
|
-
console.log(chalk.gray(' Done'));
|
|
143
129
|
|
|
144
|
-
// Create app and server
|
|
145
|
-
app = createApp(source, data, routes, middlewares, argv);
|
|
146
|
-
server = app.listen(argv.port, argv.host);
|
|
130
|
+
console.log(chalk.gray(' Done')); // Create app and server
|
|
147
131
|
|
|
148
|
-
|
|
149
|
-
|
|
132
|
+
app = createApp(db, routes, middlewares, argv);
|
|
133
|
+
server = app.listen(argv.port, argv.host); // Enhance with a destroy function
|
|
150
134
|
|
|
151
|
-
// Display server informations
|
|
152
|
-
prettyPrint(argv, data, routes);
|
|
135
|
+
enableDestroy(server); // Display server informations
|
|
153
136
|
|
|
154
|
-
|
|
137
|
+
prettyPrint(argv, db.getState(), routes); // Catch and handle any error occurring in the server process
|
|
138
|
+
|
|
139
|
+
process.on('uncaughtException', error => {
|
|
140
|
+
if (error.errno === 'EADDRINUSE') console.log(chalk.red(`Cannot bind to the port ${error.port}. Please specify another port number either through --port argument or through the json-server.json configuration file`));else console.log('Some error occurred', error);
|
|
141
|
+
process.exit(1);
|
|
142
|
+
});
|
|
155
143
|
});
|
|
156
|
-
}
|
|
144
|
+
} // Start server
|
|
157
145
|
|
|
158
|
-
// Start server
|
|
159
|
-
start(function () {
|
|
160
|
-
// Snapshot
|
|
161
|
-
console.log(chalk.gray(' Type s + enter at any time to create a snapshot of the database'));
|
|
162
146
|
|
|
163
|
-
|
|
147
|
+
start().then(() => {
|
|
148
|
+
// Snapshot
|
|
149
|
+
console.log(chalk.gray(' Type s + enter at any time to create a snapshot of the database')); // Support nohup
|
|
164
150
|
// https://github.com/typicode/json-server/issues/221
|
|
165
|
-
|
|
151
|
+
|
|
152
|
+
process.stdin.on('error', () => {
|
|
166
153
|
console.log(` Error, can't read from stdin`);
|
|
167
154
|
console.log(` Creating a snapshot from the CLI won't be possible`);
|
|
168
155
|
});
|
|
169
156
|
process.stdin.setEncoding('utf8');
|
|
170
|
-
process.stdin.on('data',
|
|
157
|
+
process.stdin.on('data', chunk => {
|
|
171
158
|
if (chunk.trim().toLowerCase() === 's') {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
159
|
+
const filename = `db-${Date.now()}.json`;
|
|
160
|
+
const file = path.join(argv.snapshots, filename);
|
|
161
|
+
const state = app.db.getState();
|
|
175
162
|
fs.writeFileSync(file, JSON.stringify(state, null, 2), 'utf-8');
|
|
176
163
|
console.log(` Saved snapshot to ${path.relative(process.cwd(), file)}\n`);
|
|
177
164
|
}
|
|
178
|
-
});
|
|
165
|
+
}); // Watch files
|
|
179
166
|
|
|
180
|
-
// Watch files
|
|
181
167
|
if (argv.watch) {
|
|
182
168
|
console.log(chalk.gray(' Watching...'));
|
|
183
169
|
console.log();
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
// Can't watch URL
|
|
187
|
-
if (is.URL(_source)) throw new Error("Can't watch URL");
|
|
170
|
+
const source = argv._[0]; // Can't watch URL
|
|
188
171
|
|
|
189
|
-
// Watch .js or .json file
|
|
172
|
+
if (is.URL(source)) throw new Error("Can't watch URL"); // Watch .js or .json file
|
|
190
173
|
// Since lowdb uses atomic writing, directory is watched instead of file
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
174
|
+
|
|
175
|
+
const watchedDir = path.dirname(source);
|
|
176
|
+
let readError = false;
|
|
177
|
+
fs.watch(watchedDir, (event, file) => {
|
|
194
178
|
// https://github.com/typicode/json-server/issues/420
|
|
195
179
|
// file can be null
|
|
196
180
|
if (file) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
181
|
+
const watchedFile = path.resolve(watchedDir, file);
|
|
182
|
+
|
|
183
|
+
if (watchedFile === path.resolve(source)) {
|
|
184
|
+
if (is.FILE(watchedFile)) {
|
|
185
|
+
let obj;
|
|
186
|
+
|
|
201
187
|
try {
|
|
202
188
|
obj = jph.parse(fs.readFileSync(watchedFile));
|
|
189
|
+
|
|
203
190
|
if (readError) {
|
|
204
191
|
console.log(chalk.green(` Read error has been fixed :)`));
|
|
205
192
|
readError = false;
|
|
@@ -209,34 +196,36 @@ module.exports = function (argv) {
|
|
|
209
196
|
console.log(chalk.red(` Error reading ${watchedFile}`));
|
|
210
197
|
console.error(e.message);
|
|
211
198
|
return;
|
|
212
|
-
}
|
|
199
|
+
} // Compare .json file content with in memory database
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
const isDatabaseDifferent = !_.isEqual(obj, app.db.getState());
|
|
213
203
|
|
|
214
|
-
// Compare .json file content with in memory database
|
|
215
|
-
var isDatabaseDifferent = !_.isEqual(obj, app.db.getState());
|
|
216
204
|
if (isDatabaseDifferent) {
|
|
217
|
-
console.log(chalk.gray(` ${
|
|
218
|
-
server && server.destroy();
|
|
219
|
-
start();
|
|
205
|
+
console.log(chalk.gray(` ${source} has changed, reloading...`));
|
|
206
|
+
server && server.destroy(() => start());
|
|
220
207
|
}
|
|
221
208
|
}
|
|
222
209
|
}
|
|
223
210
|
}
|
|
224
|
-
});
|
|
211
|
+
}); // Watch routes
|
|
225
212
|
|
|
226
|
-
// Watch routes
|
|
227
213
|
if (argv.routes) {
|
|
228
|
-
|
|
229
|
-
fs.watch(
|
|
214
|
+
const watchedDir = path.dirname(argv.routes);
|
|
215
|
+
fs.watch(watchedDir, (event, file) => {
|
|
230
216
|
if (file) {
|
|
231
|
-
|
|
217
|
+
const watchedFile = path.resolve(watchedDir, file);
|
|
218
|
+
|
|
232
219
|
if (watchedFile === path.resolve(argv.routes)) {
|
|
233
220
|
console.log(chalk.gray(` ${argv.routes} has changed, reloading...`));
|
|
234
|
-
server && server.destroy();
|
|
235
|
-
start();
|
|
221
|
+
server && server.destroy(() => start());
|
|
236
222
|
}
|
|
237
223
|
}
|
|
238
224
|
});
|
|
239
225
|
}
|
|
240
226
|
}
|
|
227
|
+
}).catch(err => {
|
|
228
|
+
console.log(err);
|
|
229
|
+
process.exit(1);
|
|
241
230
|
});
|
|
242
231
|
};
|
package/lib/cli/utils/is.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
module.exports = {
|
|
4
|
-
|
|
4
|
+
FILE,
|
|
5
5
|
JS,
|
|
6
6
|
URL
|
|
7
7
|
};
|
|
8
8
|
|
|
9
|
-
function
|
|
9
|
+
function FILE(s) {
|
|
10
10
|
return !URL(s) && /\.json$/.test(s);
|
|
11
11
|
}
|
|
12
12
|
|
|
@@ -15,6 +15,5 @@ function JS(s) {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
function URL(s) {
|
|
18
|
-
return
|
|
19
|
-
);
|
|
18
|
+
return /^(http|https):/.test(s);
|
|
20
19
|
}
|
package/lib/cli/utils/load.js
CHANGED
|
@@ -1,41 +1,74 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
request(opts, function (err, response) {
|
|
18
|
-
if (err) return cb(err);
|
|
19
|
-
cb(null, response.body);
|
|
20
|
-
});
|
|
21
|
-
} else if (is.JS(source)) {
|
|
22
|
-
// Clear cache
|
|
23
|
-
var filename = path.resolve(source);
|
|
24
|
-
delete require.cache[filename];
|
|
25
|
-
var dataFn = require(filename);
|
|
26
|
-
|
|
27
|
-
if (typeof dataFn !== 'function') {
|
|
28
|
-
throw new Error('The database is a JavaScript file but the export is not a function.');
|
|
29
|
-
}
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
|
|
5
|
+
const path = require('path');
|
|
6
|
+
|
|
7
|
+
const request = require('request');
|
|
8
|
+
|
|
9
|
+
const low = require('lowdb');
|
|
10
|
+
|
|
11
|
+
const FileAsync = require('lowdb/adapters/FileAsync');
|
|
12
|
+
|
|
13
|
+
const Memory = require('lowdb/adapters/Memory');
|
|
14
|
+
|
|
15
|
+
const is = require('./is');
|
|
30
16
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
17
|
+
const chalk = require('chalk');
|
|
18
|
+
|
|
19
|
+
const example = {
|
|
20
|
+
posts: [{
|
|
21
|
+
id: 1,
|
|
22
|
+
title: 'json-server',
|
|
23
|
+
author: 'typicode'
|
|
24
|
+
}],
|
|
25
|
+
comments: [{
|
|
26
|
+
id: 1,
|
|
27
|
+
body: 'some comment',
|
|
28
|
+
postId: 1
|
|
29
|
+
}],
|
|
30
|
+
profile: {
|
|
31
|
+
name: 'typicode'
|
|
40
32
|
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
module.exports = function (source) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
if (is.FILE(source)) {
|
|
38
|
+
if (!fs.existsSync(source)) {
|
|
39
|
+
console.log(chalk.yellow(` Oops, ${source} doesn't seem to exist`));
|
|
40
|
+
console.log(chalk.yellow(` Creating ${source} with some default data`));
|
|
41
|
+
console.log();
|
|
42
|
+
fs.writeFileSync(source, JSON.stringify(example, null, 2));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
resolve(low(new FileAsync(source)));
|
|
46
|
+
} else if (is.URL(source)) {
|
|
47
|
+
// Load remote data
|
|
48
|
+
const opts = {
|
|
49
|
+
url: source,
|
|
50
|
+
json: true
|
|
51
|
+
};
|
|
52
|
+
request(opts, (err, response) => {
|
|
53
|
+
if (err) return reject(err);
|
|
54
|
+
resolve(low(new Memory()).setState(response.body));
|
|
55
|
+
});
|
|
56
|
+
} else if (is.JS(source)) {
|
|
57
|
+
// Clear cache
|
|
58
|
+
const filename = path.resolve(source);
|
|
59
|
+
delete require.cache[filename];
|
|
60
|
+
|
|
61
|
+
const dataFn = require(filename);
|
|
62
|
+
|
|
63
|
+
if (typeof dataFn !== 'function') {
|
|
64
|
+
throw new Error('The database is a JavaScript file but the export is not a function.');
|
|
65
|
+
} // Run dataFn to generate data
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
const data = dataFn();
|
|
69
|
+
resolve(low(new Memory()).setState(data));
|
|
70
|
+
} else {
|
|
71
|
+
throw new Error(`Unsupported source ${source}`);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
41
74
|
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
require("promise-polyfill/src/polyfill");
|
|
4
|
+
|
|
5
|
+
require("whatwg-fetch");
|
|
6
|
+
|
|
7
|
+
var _preact = require("preact");
|
|
8
|
+
|
|
9
|
+
require("milligram/dist/milligram.css");
|
|
10
|
+
|
|
11
|
+
require("./style.css");
|
|
12
|
+
|
|
13
|
+
function ResourceItem(_ref) {
|
|
14
|
+
var name = _ref.name,
|
|
15
|
+
length = _ref.length;
|
|
16
|
+
return (0, _preact.h)("li", null, (0, _preact.h)("a", {
|
|
17
|
+
href: name
|
|
18
|
+
}, "/", name), " ", (0, _preact.h)("sup", null, length ? "".concat(length, "x") : 'object'));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function ResourceList(_ref2) {
|
|
22
|
+
var db = _ref2.db;
|
|
23
|
+
return (0, _preact.h)("ul", null, Object.keys(db).map(function (name) {
|
|
24
|
+
return (0, _preact.h)(ResourceItem, {
|
|
25
|
+
name: name,
|
|
26
|
+
length: Array.isArray(db[name]) && db[name].length
|
|
27
|
+
});
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function NoResources() {
|
|
32
|
+
return (0, _preact.h)("p", null, "No resources found");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function ResourcesBlock(_ref3) {
|
|
36
|
+
var db = _ref3.db;
|
|
37
|
+
return (0, _preact.h)("div", null, (0, _preact.h)("h4", null, "Resources"), Object.keys(db).length ? (0, _preact.h)(ResourceList, {
|
|
38
|
+
db: db
|
|
39
|
+
}) : (0, _preact.h)(NoResources, null));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
window.fetch('db').then(function (response) {
|
|
43
|
+
return response.json();
|
|
44
|
+
}).then(function (db) {
|
|
45
|
+
return (0, _preact.render)((0, _preact.h)(ResourcesBlock, {
|
|
46
|
+
db: db
|
|
47
|
+
}), document.getElementById('resources'));
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
function CustomRoutesBlock(_ref4) {
|
|
51
|
+
var customRoutes = _ref4.customRoutes;
|
|
52
|
+
var rules = Object.keys(customRoutes);
|
|
53
|
+
|
|
54
|
+
if (rules.length) {
|
|
55
|
+
return (0, _preact.h)("div", null, (0, _preact.h)("h4", null, "Custom Routes"), (0, _preact.h)("table", null, rules.map(function (rule) {
|
|
56
|
+
return (0, _preact.h)("tr", null, (0, _preact.h)("td", null, rule), (0, _preact.h)("td", null, "\u21E2 ", customRoutes[rule]));
|
|
57
|
+
})));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
window.fetch('__rules').then(function (response) {
|
|
62
|
+
return response.json();
|
|
63
|
+
}).then(function (customRoutes) {
|
|
64
|
+
(0, _preact.render)((0, _preact.h)(CustomRoutesBlock, {
|
|
65
|
+
customRoutes: customRoutes
|
|
66
|
+
}), document.getElementById('custom-routes'));
|
|
67
|
+
});
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
"use strict";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
const bodyParser = require('body-parser');
|
|
4
4
|
|
|
5
|
-
module.exports = [bodyParser.json({
|
|
5
|
+
module.exports = [bodyParser.json({
|
|
6
|
+
limit: '10mb',
|
|
7
|
+
extended: false
|
|
8
|
+
}), bodyParser.urlencoded({
|
|
9
|
+
extended: false
|
|
10
|
+
})];
|