UNPKG

2.19 kBJavaScriptView Raw
1
2'use strict';
3
4const _ = require('lodash');
5
6const express = require('express');
7const debug = require('debug')('motif:service');
8
9class Service {
10
11 get name() {
12 return this._name;
13 }
14
15 get path() {
16
17 if (this._type === "api") {
18 if (process.motif.context.path != "") {
19 return "/" + [process.motif.context.path, this._interfaceVersion, this._path].join("/");
20 }
21
22 return "/" + [this._interfaceVersion, this._path].join("/");
23 }
24
25 if (process.motif.context.path != "") {
26 return "/" + [process.motif.context.path, this._path].join("/");
27 }
28
29 return "/" + this._path;
30 }
31
32 get config() {
33 return this._config;
34 }
35
36 get version() {
37 return this._version;
38 }
39
40 get defaultContentType() {
41 if (this._type === "web") {
42 return 'text/html; charset=utf-8';
43 }
44
45 return 'application/json; charset=utf-8';
46 }
47
48 get contentType() {
49 return this._contentType;
50 }
51
52 get main() {
53 return this._main;
54 }
55
56 _normalizePath( val ) {
57
58 if ( val && val.indexOf("/") === 0 ) {
59 return val.substr(1);
60 }
61
62 return val;
63 }
64
65 constructor( name, options ) {
66
67 let { type, config, router, path, contentType, version, interfaceVersion, main } = options;
68
69 debug( "options", options );
70
71 this._type = type || 'api';
72 this._config = config;
73 this._name = name || '';
74 this._path = this._normalizePath(path || this._name);
75 this._contentType = contentType || this.defaultContentType;
76 this._version = version || '0.0.0';
77 this._interfaceVersion = interfaceVersion || 'v1';
78 this._main = main === true ? true : false;
79
80 this._router = router({
81 "type": this._type,
82 "app": process.motif.app,
83 "router": express.Router({strict: true}),
84 "service": this
85 });
86
87 debug( "use router", this._type, this.path, contentType, this.defaultContentType );
88
89 process.motif.app.use( this.path, this._router );
90 }
91}
92
93module.exports = Service;