1 | "use strict"
|
2 |
|
3 | const _ = require("lodash")
|
4 | const express = require("express")
|
5 | const debug = require("debug")("motif:service")
|
6 |
|
7 | class Service {
|
8 | get name() {
|
9 | return this._name
|
10 | }
|
11 |
|
12 | get path() {
|
13 | if (this._type === "api") {
|
14 | if (process.motif.context.path != "") {
|
15 | return (
|
16 | "/" + [process.motif.context.path, this._interfaceVersion, this._path].join(
|
17 | "/"
|
18 | )
|
19 | )
|
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 | if (val && val.indexOf("/") === 0) {
|
58 | return val.substr(1)
|
59 | }
|
60 |
|
61 | return val
|
62 | }
|
63 |
|
64 | constructor(name, options) {
|
65 | let { type, config, router, path, contentType, version, interfaceVersion, main } = options
|
66 |
|
67 | debug("options", options)
|
68 |
|
69 | this._type = type || "api"
|
70 | this._config = config || process.motif.context.config
|
71 | this._name = name || ""
|
72 | this._path = this._normalizePath(path || this._name)
|
73 | this._contentType = contentType || this.defaultContentType
|
74 | this._version = version || "0.0.0"
|
75 | this._interfaceVersion = interfaceVersion || process.motif.context.interfaceVersion || "v1"
|
76 | this._main = main === true ? true : false
|
77 |
|
78 | this._router = router({
|
79 | type: this._type,
|
80 | app: process.motif.app,
|
81 | router: express.Router({ strict: true }),
|
82 | service: this
|
83 | })
|
84 |
|
85 | debug("use router", this._type, this.path, contentType, this.defaultContentType)
|
86 |
|
87 | process.motif.app.use(this.path, this._router)
|
88 | }
|
89 | }
|
90 |
|
91 | module.exports = Service
|