UNPKG

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