@xmono/server 1.0.5 → 1.0.7

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/dist/index.js CHANGED
@@ -1 +1 @@
1
- (()=>{"use strict";var e={n:t=>{var r=t&&t.__esModule?()=>t.default:()=>t;return e.d(r,{a:r}),r},d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createAuthMiddleware:()=>g,createFileController:()=>O,createModelController:()=>P,createStaticMiddleware:()=>p,jwtSign:()=>x,parseQuery:()=>E,server:()=>v});const r=require("fs");var o=e.n(r);const s=require("path");var n=e.n(s);const a=require("koa");var i=e.n(a);const c=require("@koa/send"),l=require("@koa/bodyparser"),d=require("@xmono/db"),u=require("koa-range");var y=e.n(u);const p=({publicPath:e,root:t})=>(e=e.replace(/\/*$/,"/").replace(/^\/*/,"/"),async(r,o)=>{if(r.path.startsWith(e)&&["HEAD","GET"].includes(r.method)){let s=decodeURIComponent(r.path.replace(e,""));try{await(0,c.send)(r,s,{root:t})}catch{await o()}}else await o()}),f=require("@koa/router");var b=e.n(f);const h=require("koa-jwt");var m=e.n(h);const g=e=>{const t=m()({secret:e.secret,getToken:e=>e.header.authorization||e.query.token});return e.unless?t.unless({path:e.unless}):t},q=new(b()),w=async(e,t)=>t().catch(t=>{let r=500,o="";"string"==typeof t?(r=400,o=t,console.log(t)):401===t.status?(r=401,o=t.originalError?t.originalError.message:t.message):(t.status&&(r=t.status),o=t.message,console.log(t)),e.response.status=r,e.response.body=o}),S=new(i());function k(e){Array.isArray(e)||(e=[e]);const t=[];for(let r of e)"function"==typeof r.keys?r.keys().forEach(e=>{t.push(r(e).default)}):t.push(r);return t}const v={async start(e={}){const t=n().resolve("config.js");o().existsSync(t)&&Object.assign(e,require(t)),this.config=e;let{db:r,host:s,port:a=8080,public:i="dist/public",models:u,controllers:f,index:b="dist/public/index.html",middlewares:h=[]}=e;if(u&&(u=k(u)),f&&(f=k(f)),r&&(!0===r&&(r={client:"sqlite3",connection:{filename:n().resolve("data.db")}}),await d.DBUtil.init(r,u)),S.use(w),S.use((0,l.bodyParser)({parsedMethods:["PUT","POST","DELETE"]})),S.use((e=>{if(e){const{auth:t}=v.config;t&&q.use(g(t));for(let t of e)for(let e in t){const r=e.split(" ");if(2!==r.length)throw"controller key error: "+e;{const[o,s]=r;if(!["get","post","put","delete"].includes(o))throw"controller method error: "+o;q[o]("/api"+s,t[e])}}}return q.routes()})(f)),i)if(S.use(y()),Array.isArray(i))for(let e of i)S.use(p(e));else"string"==typeof i&&(i=[{publicPath:"/",root:i,index:b}]),S.use(p(i));for(let e of h)S.use(e);return b&&S.use(async e=>await(0,c.send)(e,b)),new Promise(e=>{const t=S.listen(a,s,()=>{const r=t.address();console.log(`server listen on [${r.address}]:${r.port}`),e(t)})})}},$=require("jsonwebtoken");var j=e.n($);const x=(e,t,r)=>j().sign(e,t,{expiresIn:r}),E=e=>{let t=null,r=null,o=null,s=null,n=null;for(let a in e)switch(a){case"fields":r=e[a].split(",");break;case"sort":{o=o||[];const t=e[a].split(",");for(let e=0;e<t.length;e+=2)o.push({column:t[e],order:t[e+1]});break}case"size":case"page":s=s||{},s[a]=e[a]-0;break;case"search":n=e[a];break;default:{let r=decodeURIComponent(e[a]);a.startsWith("!")?(a=a.substring(1),r=["!=",r]):a.startsWith("*")&&(a=a.substring(1),r=["like",`%${r}%`]),r&&(t=t||{},t[a]=r)}}return{condition:{where:t},options:{fields:r,sort:o,pager:s},search:n}},P=e=>{const t=e.key||"id",r=e.table;async function o(t){const{condition:r,options:o,search:s}=E(t.query);if(s){const t=[];e.columns.forEach(e=>{e.matchSearch&&t.push({[e.name]:["like",`%${s}%`]})}),t.length&&(r.orWhere=t)}let n=await e.find(r,o);t.callback&&(n=t.callback(n)),o.pager?t.body={data:n,pager:o.pager}:t.body=n}async function s(r){const{options:o}=E(r.query);let s=await e.findById(r.params[t],o.fields);r.body=r.callback?r.callback(s):s}async function n(t){t.body=await e.save(t.request.body)}async function a(r){r.body=await e.deleteById(r.request.body[t])}async function i(r){r.body=await e.updateById(r.params[t],r.request.body)}return o.req=`get /${r}`,s.req=`get /${r}/:${t}`,n.req=`post /${r}`,i.req=`put /${r}/:${t}`,a.req=`delete /${r}`,{all:function(){return{[o.req]:o,[s.req]:s,[n.req]:n,[i.req]:i,[a.req]:a}},list:o,get:s,post:n,put:i,delete:a}},A=require("@koa/multer");var F=e.n(A);const O=(e={})=>{const{prefix:t="/files",getFullPath:r=e=>e}=e,s=F()({storage:{_handleFile(e,t,s){let a=r(e.body.path),{hash:i,index:c,name:l}=e.body;i&&(a=n().join(a,i)),a=void 0!==c?n().join(a,c):n().join(a,l);const d=n().dirname(a);o().existsSync(d)||o().mkdirSync(d,{recursive:!0});const u=o().createWriteStream(a);t.stream.pipe(u),u.on("finish",()=>{s(null,{path:a,size:u.bytesWritten})}),e.on("aborted",()=>{t.stream.on("end",()=>{o().rmSync(a,{recursive:!0,force:!0})}),t.stream.emit("end")})},_removeFile(e,t,r){o().remove(t.path,r)}}});return{[`get ${t}/{*path}`]:async e=>{const t=r(e.params.path);if(o().existsSync(t))return await(0,c.send)(e,n().basename(t),{root:n().dirname(t)});throw"无效路径"},[`post ${t}/readdir`]:async e=>{const t=r(e.request.body.path),s=e.request.body.fields||[],a=[];o().existsSync(t)&&o().readdirSync(t).forEach(e=>{let r={name:e};const i=o().statSync(n().join(t,e));if(i.isDirectory())r.dir=1;else for(let e of s)r[e]=i[e];a.push(r)}),e.body=a},[`post ${t}/readfile`]:async e=>{const t=r(e.request.body.path);if(!o().existsSync(t))throw"无效路径";await(0,c.send)(e,n().basename(t),{root:n().dirname(t)})},[`post ${t}/remove`]:async e=>{let{path:t}=e.request.body;Array.isArray(t)||(t=[t]),t.forEach(e=>{o().rmSync(r(e),{recursive:!0,force:!0})}),e.body=""},[`post ${t}/upload`]:async(e,t)=>{const r=s.single("file");await r(e,t),e.body=""},[`post ${t}/mkdir`]:async e=>{const t=r(e.request.body.path);o().mkdirSync(t),e.body=""},[`post ${t}/writefile`]:async e=>{const{content:t,path:s}=e.request.body,n=r(s);o().writeFileSync(n,t),e.body=""},[`post ${t}/rename`]:async e=>{let{from:t,to:s}=e.request.body;const n=r(t),a=r(s);o().renameSync(n,a),e.body=""},[`post ${t}/copy`]:async e=>{let{from:t,to:s}=e.request.body;const n=r(t),a=r(s);o().copySync(n,a,{overwrite:!1,errorOnExist:!0}),e.body=""},[`post ${t}/merge`]:async e=>{const{total:t,hash:s,name:a}=e.request.body,i=r(e.request.body.path),c=n().join(i,s),l=n().join(i,a);o().writeFileSync(l,"");for(let e=0;e<t;e++)o().appendFileSync(l,o().readFileSync(c+"/"+e));o().rmSync(c,{recursive:!0,force:!0}),e.body=""}}};module.exports=t})();
1
+ (()=>{"use strict";var e={n:t=>{var r=t&&t.__esModule?()=>t.default:()=>t;return e.d(r,{a:r}),r},d:(t,r)=>{for(var o in r)e.o(r,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:r[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createAuthMiddleware:()=>g,createFileController:()=>F,createModelController:()=>P,createStaticMiddleware:()=>p,jwtSign:()=>x,parseQuery:()=>E,server:()=>S});const r=require("fs");var o=e.n(r);const s=require("path");var n=e.n(s);const a=require("koa");var i=e.n(a);const c=require("@koa/send"),l=require("@koa/bodyparser"),d=require("@xmono/db"),u=require("koa-range");var y=e.n(u);const p=({publicPath:e,root:t})=>(e=e.replace(/\/*$/,"/").replace(/^\/*/,"/"),async(r,o)=>{if(r.path.startsWith(e)&&["HEAD","GET"].includes(r.method)){let s=decodeURIComponent(r.path.replace(e,""));try{await(0,c.send)(r,s,{root:t})}catch{await o()}}else await o()}),f=require("@koa/router");var b=e.n(f);const h=require("koa-jwt");var m=e.n(h);const g=e=>{const t=m()({secret:e.secret,getToken:e=>e.header.authorization||e.query.token});return e.unless?t.unless({path:e.unless}):t},$=new(b()),w=async(e,t)=>t().catch(t=>{let r=500,o="";"string"==typeof t?(r=400,o=t,console.log(t)):401===t.status?(r=401,o=t.originalError?t.originalError.message:t.message):(t.status&&(r=t.status),o=t.message,console.log(t)),e.response.status=r,e.response.body=o}),k=new(i());function q(e){Array.isArray(e)||(e=[e]);const t=[];for(let r of e)"function"==typeof r.keys?r.keys().forEach(e=>{t.push(r(e).default)}):t.push(r);return t}const S={async start(e={}){const t=n().resolve("config.js");o().existsSync(t)&&Object.assign(e,require(t)),this.config=e;let{db:r,host:s,port:a=8080,public:i="dist/public",models:u,controllers:f,index:b="dist/public/index.html",middlewares:h=[]}=e;if(u&&(u=q(u)),f&&(f=q(f)),r&&(!0===r&&(r={client:"sqlite3",connection:{filename:n().resolve("data.db")}}),await d.DBUtil.init(r,u)),k.use(w),k.use((0,l.bodyParser)({parsedMethods:["PUT","POST","DELETE"]})),k.use((e=>{if(e){const{auth:t}=S.config;t&&$.use(g(t));for(let t of e)for(let e in t){const r=e.split(" ");if(2!==r.length)throw"controller key error: "+e;{const[o,s]=r;if(!["get","post","put","delete"].includes(o))throw"controller method error: "+o;$[o]("/api"+s,t[e])}}}return $.routes()})(f)),i)if(k.use(y()),Array.isArray(i))for(let e of i)k.use(p(e));else"string"==typeof i&&(i=[{publicPath:"/",root:i,index:b}]),k.use(p(i));for(let e of h)k.use(e);return b&&k.use(async e=>await(0,c.send)(e,b)),new Promise(e=>{const t=k.listen(a,s,()=>{const r=t.address();console.log(`server listen on [${r.address}]:${r.port}`),e(t)})})}},v=require("jsonwebtoken");var j=e.n(v);const x=(e,t,r)=>j().sign(e,t,{expiresIn:r}),E=e=>{let t=null,r=null,o=null,s=null,n=null;for(let a in e)switch(a){case"fields":r=e[a].split(",");break;case"sort":{o=o||[];const t=e[a].split(",");for(let e=0;e<t.length;e+=2)o.push({column:t[e],order:t[e+1]});break}case"size":case"page":s=s||{},s[a]=e[a]-0;break;case"search":n=e[a];break;default:{let r=decodeURIComponent(e[a]);a.startsWith("!")?(a=a.substring(1),r=["!=",r]):a.startsWith("*")&&(a=a.substring(1),r=["like",`%${r}%`]),r&&(t=t||{},t[a]=r)}}return{condition:{where:t},options:{fields:r,sort:o,pager:s},search:n}},P=(e,t,r)=>{const o=e.key||"id",s=e.table,n={$list:`get /${s}`,$get:`get /${s}/:${o}`,$post:`post /${s}`,$put:`put /${s}/:${o}`,$delete:`delete /${s}`};async function a(t){const{condition:r,options:o,search:s}=E(t.query);if(s){const t=[];e.columns.forEach(e=>{e.matchSearch&&t.push({[e.name]:["like",`%${s}%`]})}),t.length&&(r.orWhere=t)}let n=await e.find(r,o);t.callback&&(n=await t.callback(n)),o.pager?t.body={data:n,pager:o.pager}:t.body=n}async function i(t){const{options:r}=E(t.query);let s=await e.findById(t.params[o],r.fields);t.body=t.callback?t.callback(s):s}async function c(t){t.body=await e.save(t.request.body)}async function l(t){t.body=await e.deleteById(t.request.body[o])}async function d(t){t.body=await e.updateById(t.params[o],t.request.body)}let u={},y={};if(t&&"object"!=typeof t&&"function"!=typeof t){Array.isArray(t)||(t=[t]);for(let e of t)switch(e){case"list":y[n.$list]=a;break;case"get":y[n.$get]=i;break;case"post":y[n.$post]=c;break;case"put":y[n.$put]=d;break;case"delete":y[n.$delete]=l}}else y={[n.$list]:a,[n.$get]:i,[n.$post]:c,[n.$put]:d,[n.$delete]:l},r=t;if(r){"function"==typeof r&&(r=r({list:a,get:i,put:d,post:c,delete:l}));for(let e in r){const t=r[e];n[e]&&(e=n[e]),y[e]?y[e]=t:u[e]=t}}return Object.assign(u,y),u},A=require("@koa/multer");var O=e.n(A);const F=(e={})=>{const{prefix:t="/files",getFullPath:r=e=>e}=e,s=O()({storage:{_handleFile(e,t,s){let a=r(e.body.path),{hash:i,index:c,name:l}=e.body;i&&(a=n().join(a,i)),a=void 0!==c?n().join(a,c):n().join(a,l);const d=n().dirname(a);o().existsSync(d)||o().mkdirSync(d,{recursive:!0});const u=o().createWriteStream(a);t.stream.pipe(u),u.on("finish",()=>{s(null,{path:a,size:u.bytesWritten})}),e.on("aborted",()=>{t.stream.on("end",()=>{o().rmSync(a,{recursive:!0,force:!0})}),t.stream.emit("end")})},_removeFile(e,t,r){o().remove(t.path,r)}}});return{[`get ${t}/{*path}`]:async e=>{const t=r(e.params.path);if(o().existsSync(t))return await(0,c.send)(e,n().basename(t),{root:n().dirname(t)});throw"无效路径"},[`post ${t}/readdir`]:async e=>{const t=r(e.request.body.path),s=e.request.body.fields||[],a=[];o().existsSync(t)&&o().readdirSync(t).forEach(e=>{let r={name:e};const i=o().statSync(n().join(t,e));if(i.isDirectory())r.dir=1;else for(let e of s)r[e]=i[e];a.push(r)}),e.body=a},[`post ${t}/readfile`]:async e=>{const t=r(e.request.body.path);if(!o().existsSync(t))throw"无效路径";await(0,c.send)(e,n().basename(t),{root:n().dirname(t)})},[`post ${t}/remove`]:async e=>{let{path:t}=e.request.body;Array.isArray(t)||(t=[t]),t.forEach(e=>{o().rmSync(r(e),{recursive:!0,force:!0})}),e.body=""},[`post ${t}/upload`]:async(e,t)=>{const r=s.single("file");await r(e,t),e.body=""},[`post ${t}/mkdir`]:async e=>{const t=r(e.request.body.path);o().mkdirSync(t),e.body=""},[`post ${t}/writefile`]:async e=>{const{content:t,path:s}=e.request.body,n=r(s);o().writeFileSync(n,t),e.body=""},[`post ${t}/rename`]:async e=>{let{from:t,to:s}=e.request.body;const n=r(t),a=r(s);o().renameSync(n,a),e.body=""},[`post ${t}/copy`]:async e=>{let{from:t,to:s}=e.request.body;const n=r(t),a=r(s);o().copySync(n,a,{overwrite:!1,errorOnExist:!0}),e.body=""},[`post ${t}/merge`]:async e=>{const{total:t,hash:s,name:a}=e.request.body,i=r(e.request.body.path),c=n().join(i,s),l=n().join(i,a);o().writeFileSync(l,"");for(let e=0;e<t;e++)o().appendFileSync(l,o().readFileSync(c+"/"+e));o().rmSync(c,{recursive:!0,force:!0}),e.body=""}}};module.exports=t})();
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","mappings":";;;;;;;;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;AClKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;ACtBA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;AC7DA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;;;;;ACAA;;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACPA;;;;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;ACNA;AACA;AACA;AACA;AACA;AACA","sources":["webpack://@xmono/server/./src/middlewares/ErrorHandlerMiddleware.js","webpack://@xmono/server/./src/server.js","webpack://@xmono/server/./src/utils/createAuthMiddleware.js","webpack://@xmono/server/./src/utils/createControllerMiddleware.js","webpack://@xmono/server/./src/utils/createFileController.js","webpack://@xmono/server/./src/utils/createModelController.js","webpack://@xmono/server/./src/utils/createStaticMiddleware.js","webpack://@xmono/server/./src/utils/jwtSign.js","webpack://@xmono/server/./src/utils/parseQuery.js","webpack://@xmono/server/external commonjs \"@koa/bodyparser\"","webpack://@xmono/server/external commonjs \"@koa/multer\"","webpack://@xmono/server/external commonjs \"@koa/router\"","webpack://@xmono/server/external commonjs \"@koa/send\"","webpack://@xmono/server/external commonjs \"@xmono/db\"","webpack://@xmono/server/external node-commonjs \"fs\"","webpack://@xmono/server/external commonjs \"jsonwebtoken\"","webpack://@xmono/server/external commonjs \"koa\"","webpack://@xmono/server/external commonjs \"koa-jwt\"","webpack://@xmono/server/external commonjs \"koa-range\"","webpack://@xmono/server/external node-commonjs \"path\"","webpack://@xmono/server/webpack/bootstrap","webpack://@xmono/server/webpack/runtime/compat get default export","webpack://@xmono/server/webpack/runtime/define property getters","webpack://@xmono/server/webpack/runtime/hasOwnProperty shorthand","webpack://@xmono/server/webpack/runtime/make namespace object","webpack://@xmono/server/./src/index.js"],"sourcesContent":["export default async (ctx, next) => {\r\n return next().catch(err => {\r\n let status = 500, message = '';\r\n if (typeof err === 'string') {\r\n status = 400;\r\n message = err;\r\n console.log(err);\r\n } else if (err.status === 401) {\r\n status = 401;\r\n if (err.originalError) {\r\n message = err.originalError.message;\r\n } else {\r\n message = err.message;\r\n }\r\n } else {\r\n if (err.status) {\r\n status = err.status;\r\n }\r\n message = err.message;\r\n console.log(err);\r\n }\r\n\r\n ctx.response.status = status;\r\n ctx.response.body = message;\r\n });\r\n};","import fs from 'fs';\r\nimport path from 'path';\r\nimport Koa from 'koa';\r\nimport { send } from '@koa/send';\r\nimport { bodyParser } from '@koa/bodyparser';\r\nimport { DBUtil } from '@xmono/db';\r\nimport KoaRange from 'koa-range';\r\nimport createStaticMiddleware from './utils/createStaticMiddleware';\r\nimport createControllerMiddleware from './utils/createControllerMiddleware';\r\nimport ErrorHandlerMiddleware from './middlewares/ErrorHandlerMiddleware';\r\n\r\nconst app = new Koa();\r\n\r\nfunction loadModules(contexts) {\r\n if (!Array.isArray(contexts)) {\r\n contexts = [contexts];\r\n }\r\n const modules = [];\r\n for (let context of contexts) {\r\n if (typeof context.keys === 'function') {\r\n context.keys().forEach(name => {\r\n modules.push(context(name).default);\r\n });\r\n } else {\r\n modules.push(context);\r\n }\r\n }\r\n return modules;\r\n}\r\n\r\nexport default {\r\n\r\n async start(config = {}) {\r\n const configPath = path.resolve('config.js');\r\n if (fs.existsSync(configPath)) {\r\n // eslint-disable-next-line no-undef\r\n Object.assign(config, __non_webpack_require__(configPath));\r\n }\r\n\r\n this.config = config;\r\n\r\n let { db, host, port = 8080, public: publicConfigs = 'dist/public', models, controllers, index = 'dist/public/index.html', middlewares = [] } = config;\r\n\r\n if (models) {\r\n models = loadModules(models);\r\n }\r\n\r\n if (controllers) {\r\n controllers = loadModules(controllers);\r\n }\r\n\r\n if (db) {\r\n if (db === true) {\r\n db = {\r\n client: 'sqlite3',\r\n connection: {\r\n filename: path.resolve('data.db')\r\n }\r\n };\r\n }\r\n await DBUtil.init(db, models);\r\n }\r\n\r\n app.use(ErrorHandlerMiddleware);\r\n\r\n app.use(bodyParser({\r\n parsedMethods: ['PUT', 'POST', 'DELETE']\r\n }));\r\n\r\n app.use(createControllerMiddleware(controllers));\r\n \r\n if (publicConfigs) {\r\n app.use(KoaRange);\r\n\r\n if (!Array.isArray(publicConfigs)) {\r\n if (typeof publicConfigs === 'string') {\r\n publicConfigs = [{\r\n publicPath: '/',\r\n root: publicConfigs,\r\n index\r\n }];\r\n }\r\n app.use(createStaticMiddleware(publicConfigs));\r\n } else {\r\n for (let publicConfig of publicConfigs) {\r\n app.use(createStaticMiddleware(publicConfig));\r\n }\r\n }\r\n }\r\n\r\n for (let middleware of middlewares) {\r\n app.use(middleware);\r\n }\r\n\r\n if (index) {\r\n app.use(async ctx => await send(ctx, index));\r\n }\r\n\r\n return new Promise(resolve => {\r\n const server = app.listen(port, host, () => {\r\n const address = server.address();\r\n console.log(`server listen on [${address.address}]:${address.port}`);\r\n resolve(server);\r\n });\r\n });\r\n }\r\n};","import koaJWT from 'koa-jwt';\r\n\r\nexport default config => {\r\n const jwt = koaJWT({\r\n secret: config.secret,\r\n getToken: ctx => {\r\n return ctx.header.authorization || ctx.query.token;\r\n }\r\n });\r\n if (config.unless) {\r\n return jwt.unless({ path: config.unless });\r\n }\r\n return jwt;\r\n};","import Router from '@koa/router';\r\nimport createAuthMiddleware from './createAuthMiddleware';\r\nimport server from '../server';\r\nconst router = new Router();\r\n\r\nexport default controllers => {\r\n if (controllers) {\r\n const { auth } = server.config;\r\n if (auth) {\r\n router.use(createAuthMiddleware(auth));\r\n }\r\n for (let controller of controllers) {\r\n for (let key in controller) {\r\n const arr = key.split(' ');\r\n if (arr.length !== 2) {\r\n throw 'controller key error: ' + key;\r\n } else {\r\n const [method, path] = arr;\r\n if (!['get', 'post', 'put', 'delete'].includes(method)) {\r\n throw 'controller method error: ' + method;\r\n }\r\n router[method]('/api' + path, controller[key]);\r\n }\r\n }\r\n }\r\n }\r\n return router.routes();\r\n};","import fs from 'fs';\r\nimport path from 'path';\r\nimport { send } from '@koa/send';\r\nimport multer from '@koa/multer';\r\nexport default (config = {}) => {\r\n const { prefix = '/files', getFullPath = relativePath => relativePath } = config;\r\n const FileUploader = multer({\r\n storage: {\r\n _handleFile(req, file, cb) {\r\n\r\n let fullPath = getFullPath(req.body.path);\r\n let { hash, index, name } = req.body;\r\n if (hash) {\r\n fullPath = path.join(fullPath, hash);\r\n }\r\n\r\n if (index !== undefined) {\r\n fullPath = path.join(fullPath, index);\r\n } else {\r\n fullPath = path.join(fullPath, name);\r\n }\r\n\r\n const dir = path.dirname(fullPath);\r\n if (!fs.existsSync(dir)) {\r\n fs.mkdirSync(dir, { recursive: true });\r\n }\r\n const outStream = fs.createWriteStream(fullPath);\r\n\r\n file.stream.pipe(outStream);\r\n outStream.on('finish', () => {\r\n cb(null, {\r\n path: fullPath,\r\n size: outStream.bytesWritten\r\n });\r\n });\r\n\r\n req.on('aborted', () => {\r\n file.stream.on('end', () => {\r\n fs.rmSync(fullPath, {\r\n recursive: true,\r\n force: true\r\n });\r\n });\r\n file.stream.emit('end');\r\n });\r\n },\r\n\r\n _removeFile(req, file, cb) {\r\n fs.remove(file.path, cb);\r\n }\r\n }\r\n });\r\n\r\n return {\r\n [`get ${prefix}/{*path}`]: async ctx => {\r\n const fullPath = getFullPath(ctx.params.path);\r\n if (fs.existsSync(fullPath)) {\r\n return await send(ctx, path.basename(fullPath), { root: path.dirname(fullPath) });\r\n } else {\r\n throw '无效路径';\r\n }\r\n },\r\n\r\n [`post ${prefix}/readdir`]: async ctx => {\r\n const fullPath = getFullPath(ctx.request.body.path);\r\n const fields = ctx.request.body.fields || [];\r\n const items = [];\r\n if (fs.existsSync(fullPath)) {\r\n const list = fs.readdirSync(fullPath);\r\n list.forEach(name => {\r\n let item = { name };\r\n const stat = fs.statSync(path.join(fullPath, name));\r\n if (stat.isDirectory()) {\r\n item.dir = 1;\r\n } else {\r\n for (let field of fields) {\r\n item[field] = stat[field];\r\n }\r\n }\r\n items.push(item);\r\n });\r\n }\r\n ctx.body = items;\r\n },\r\n\r\n [`post ${prefix}/readfile`]: async ctx => {\r\n const fullPath = getFullPath(ctx.request.body.path);\r\n if (fs.existsSync(fullPath)) {\r\n await send(ctx, path.basename(fullPath), { root: path.dirname(fullPath) });\r\n } else {\r\n throw '无效路径';\r\n }\r\n },\r\n\r\n [`post ${prefix}/remove`]: async ctx => {\r\n let { path: paths } = ctx.request.body;\r\n if (!Array.isArray(paths)) {\r\n paths = [paths];\r\n }\r\n paths.forEach(path => {\r\n fs.rmSync(getFullPath(path), {\r\n recursive: true,\r\n force: true\r\n });\r\n });\r\n ctx.body = '';\r\n },\r\n\r\n [`post ${prefix}/upload`]: async (ctx, next) => {\r\n const upload = FileUploader.single('file');\r\n await upload(ctx, next);\r\n ctx.body = '';\r\n },\r\n\r\n [`post ${prefix}/mkdir`]: async ctx => {\r\n const fullPath = getFullPath(ctx.request.body.path);\r\n fs.mkdirSync(fullPath);\r\n ctx.body = '';\r\n },\r\n\r\n [`post ${prefix}/writefile`]: async ctx => {\r\n const { content, path } = ctx.request.body;\r\n const fullPath = getFullPath(path);\r\n fs.writeFileSync(fullPath, content);\r\n ctx.body = '';\r\n },\r\n\r\n [`post ${prefix}/rename`]: async ctx => {\r\n let { from, to } = ctx.request.body;\r\n const fromFullPath = getFullPath(from);\r\n const toFullPath = getFullPath(to);\r\n fs.renameSync(fromFullPath, toFullPath);\r\n ctx.body = '';\r\n },\r\n\r\n [`post ${prefix}/copy`]: async ctx => {\r\n let { from, to } = ctx.request.body;\r\n const fromFullPath = getFullPath(from);\r\n const toFullPath = getFullPath(to);\r\n fs.copySync(fromFullPath, toFullPath, { overwrite: false, errorOnExist: true });\r\n ctx.body = '';\r\n },\r\n\r\n [`post ${prefix}/merge`]: async ctx => {\r\n const { total, hash, name } = ctx.request.body;\r\n const fullPath = getFullPath(ctx.request.body.path);\r\n const chunksPath = path.join(fullPath, hash);\r\n const filePath = path.join(fullPath, name);\r\n\r\n fs.writeFileSync(filePath, '');\r\n for (let i = 0; i < total; i++) {\r\n fs.appendFileSync(filePath, fs.readFileSync(chunksPath + '/' + i));\r\n }\r\n\r\n fs.rmSync(chunksPath, {\r\n recursive: true,\r\n force: true\r\n });\r\n\r\n ctx.body = '';\r\n }\r\n };\r\n};","import parseQuery from './parseQuery';\r\nexport default (model, methods, customRoutes) => {\r\n const key = model.key || 'id';\r\n const modelName = model.table;\r\n\r\n const map = {\r\n $list: `get /${modelName}`,\r\n $get: `get /${modelName}/:${key}`,\r\n $post: `post /${modelName}`,\r\n $put: `put /${modelName}/:${key}`,\r\n $delete: `delete /${modelName}`\r\n };\r\n\r\n async function list(ctx) {\r\n const { condition, options, search } = parseQuery(ctx.query);\r\n if (search) {\r\n const orWhere = [];\r\n model.columns.forEach(column => {\r\n if (column.matchSearch) {\r\n orWhere.push({ [column.name]: ['like', `%${search}%`] });\r\n }\r\n });\r\n if (orWhere.length) {\r\n condition.orWhere = orWhere;\r\n }\r\n }\r\n let records = await model.find(condition, options);\r\n if (ctx.callback) {\r\n records = ctx.callback(records);\r\n }\r\n if (options.pager) {\r\n ctx.body = {\r\n data: records,\r\n pager: options.pager\r\n };\r\n } else {\r\n ctx.body = records;\r\n }\r\n }\r\n\r\n async function get(ctx) {\r\n const { options } = parseQuery(ctx.query);\r\n let record = await model.findById(ctx.params[key], options.fields);\r\n ctx.body = ctx.callback ? ctx.callback(record) : record;\r\n }\r\n\r\n async function post(ctx) {\r\n ctx.body = await model.save(ctx.request.body);\r\n }\r\n\r\n async function del(ctx) {\r\n ctx.body = await model.deleteById(ctx.request.body[key]);\r\n }\r\n\r\n async function put(ctx) {\r\n ctx.body = await model.updateById(ctx.params[key], ctx.request.body);\r\n }\r\n\r\n let routes = {};\r\n let extendRoutes = {};\r\n if (!methods || typeof methods === 'object' || typeof methods === 'function') {\r\n extendRoutes = {\r\n [map.$list]: list,\r\n [map.$get]: get,\r\n [map.$post]: post,\r\n [map.$put]: put,\r\n [map.$delete]: del\r\n };\r\n customRoutes = methods;\r\n } else {\r\n if (!Array.isArray(methods)) {\r\n methods = [methods];\r\n }\r\n\r\n for (let method of methods) {\r\n switch (method) {\r\n case 'list':\r\n extendRoutes[map.$list] = list;\r\n break;\r\n case 'get':\r\n extendRoutes[map.$get] = get;\r\n break;\r\n case 'post':\r\n extendRoutes[map.$post] = post;\r\n break;\r\n case 'put':\r\n extendRoutes[map.$put] = put;\r\n break;\r\n case 'delete':\r\n extendRoutes[map.$delete] = del;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n if (customRoutes) {\r\n if (typeof customRoutes === 'function') {\r\n customRoutes = customRoutes({ list, get, put, post, delete: del });\r\n }\r\n for (let key in customRoutes) {\r\n const fun = customRoutes[key];\r\n if (map[key]) {\r\n key = map[key];\r\n }\r\n if (extendRoutes[key]) {\r\n extendRoutes[key] = fun;\r\n } else {\r\n routes[key] = fun;\r\n }\r\n }\r\n }\r\n\r\n Object.assign(routes, extendRoutes);\r\n\r\n return routes;\r\n};","import { send } from '@koa/send';\r\n\r\nfunction normalize(pathname) {\r\n return pathname.replace(/\\/*$/, '/').replace(/^\\/*/, '/');\r\n}\r\n\r\nexport default ({ publicPath, root }) => {\r\n\r\n publicPath = normalize(publicPath);\r\n\r\n return async (ctx, next) => {\r\n if (ctx.path.startsWith(publicPath) && ['HEAD', 'GET'].includes(ctx.method)) {\r\n let relativePath = decodeURIComponent(ctx.path.replace(publicPath, ''));\r\n try {\r\n await send(ctx, relativePath, { root });\r\n } catch {\r\n await next();\r\n }\r\n } else {\r\n await next();\r\n }\r\n };\r\n};","import jwt from 'jsonwebtoken';\r\n\r\nexport default (payload, secret, expires) => {\r\n return jwt.sign(payload, secret, { expiresIn: expires });\r\n};","export default query => {\r\n let where = null;\r\n let fields = null;\r\n let sort = null;\r\n let pager = null;\r\n let search = null;\r\n\r\n for (let key in query) {\r\n switch (key) {\r\n case 'fields': {\r\n fields = query[key].split(',');\r\n break;\r\n }\r\n\r\n case 'sort': {\r\n sort = sort || [];\r\n const arr = query[key].split(',');\r\n for (let i = 0; i < arr.length; i += 2) {\r\n sort.push({\r\n column: arr[i],\r\n order: arr[i + 1]\r\n });\r\n }\r\n break;\r\n }\r\n case 'size':\r\n case 'page':\r\n pager = pager || {};\r\n pager[key] = query[key] - 0;\r\n break;\r\n case 'search':\r\n search = query[key];\r\n break;\r\n default: {\r\n let value = decodeURIComponent(query[key]);\r\n if (key.startsWith('!')) {\r\n key = key.substring(1);\r\n value = ['!=', value];\r\n } else if (key.startsWith('*')) {\r\n key = key.substring(1);\r\n value = ['like', `%${value}%`];\r\n }\r\n if (value) {\r\n where = where || {};\r\n where[key] = value;\r\n }\r\n }\r\n }\r\n }\r\n \r\n return {\r\n condition: {\r\n where\r\n },\r\n options: {\r\n fields,\r\n sort,\r\n pager\r\n },\r\n search\r\n };\r\n};","module.exports = require(\"@koa/bodyparser\");","module.exports = require(\"@koa/multer\");","module.exports = require(\"@koa/router\");","module.exports = require(\"@koa/send\");","module.exports = require(\"@xmono/db\");","module.exports = require(\"fs\");","module.exports = require(\"jsonwebtoken\");","module.exports = require(\"koa\");","module.exports = require(\"koa-jwt\");","module.exports = require(\"koa-range\");","module.exports = require(\"path\");","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Check if module exists (development only)\n\tif (__webpack_modules__[moduleId] === undefined) {\n\t\tvar e = new Error(\"Cannot find module '\" + moduleId + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","export { default as server } from './server';\r\nexport { default as jwtSign } from './utils/jwtSign';\r\nexport { default as parseQuery } from './utils/parseQuery';\r\nexport { default as createStaticMiddleware } from './utils/createStaticMiddleware';\r\nexport { default as createAuthMiddleware } from './utils/createAuthMiddleware';\r\nexport { default as createModelController } from './utils/createModelController';\r\nexport { default as createFileController } from './utils/createFileController';"],"names":[],"ignoreList":[],"sourceRoot":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmono/server",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "author": "wangxing",
5
5
  "description": "",
6
6
  "license": "MIT",