UNPKG

@expressive-analytics/deep-thought-service

Version:

Typescript conversion of Deep Thought Services (formerly providers)

95 lines (83 loc) 1.95 kB
import {DTModel} from '@expressive-analytics/deep-thought-js' export enum DTErr { NONE = 0, INVALID_KEY, FAILED_QUERY, PROHIBITED_ACTION, UNAUTHORIZED_TOKEN, OAUTH_CONSUMER_KEY_REFUSED } export class DTResponse{ public obj; protected err = 0; public as_proxy = false; rsp constructor(rsp,obj?,err=0){ this.obj = obj; this.err = err; this.rsp = rsp } sendHeader(header:string){ //this.rsp.setHeader(header) this.rsp.writeHead(header) } setResponse(obj){ this.obj = obj; } error(code?){ if(code!==undefined) this.err = parseInt(code); return this.err; } /** Converts the +obj+ to a form it can be rendered. For DTModels, these are only the public properties. */ objectAsRenderable(obj?,$public?){ if(obj===null) return null let renderable if(obj instanceof DTModel){ if($public===undefined) renderable = obj.toJson(); else renderable = obj.to($public) } else if(Array.isArray(obj)){ renderable = [] for(let v of obj) renderable.push(this.objectAsRenderable(v,$public)) } else if (typeof obj === 'object'){ renderable = {} Object.entries(obj).forEach(([k,v],index)=>{ renderable[k] = this.objectAsRenderable(v); }) } else renderable = obj; return renderable; } //=================== //! Rendering Methods //=================== renderAsDTR(){ let response = {"fmt":"DTR","err":this.err,"obj":this.objectAsRenderable(this.obj)}; this.render(JSON.stringify(response)); } renderAsJSON(){ this.render(JSON.stringify(this.objectAsRenderable(this.obj))); } render(str){ this.rsp.end(str); } respond(params={}){ const fmt = (typeof params["fmt"] === 'undefined')?"dtr":params["fmt"] if(this.err >= 400) // put this in the header this.rsp.sendStatus(this.err); else{ switch(fmt){ case "json": this.renderAsJSON(); break; default: this.renderAsDTR(); } } } }