ThinkJS 提供了靈活的配置,可以在不同模式下使用不同的配置,且這些配置在服務(wù)啟動(dòng)時(shí)就已經(jīng)生效,后續(xù)邏輯處理中可以直接使用這些配置。
注意:不可將一個(gè) http 請(qǐng)求中的私有值設(shè)置到配置中,這將會(huì)被下一個(gè) http 設(shè)置的值給沖掉。
ThinkJS 默認(rèn)支持 3 種項(xiàng)目環(huán)境,可以根據(jù)不同的環(huán)境進(jìn)行配置,以滿足不同情況下的配置需要。
development
開發(fā)環(huán)境testing
測試環(huán)境production
線上環(huán)境項(xiàng)目里也可以擴(kuò)展其他的環(huán)境,當(dāng)前使用哪種環(huán)境可以在 入口文件 中設(shè)置,設(shè)置 env
值即可。
項(xiàng)目里可以設(shè)置公共配置文件和模塊下的配置文件:
src/common/config
src/[module]/config
存放一些基本的配置,如:
export default {
port: 8360,
host: "",
encoding: "utf-8",
...
}
存放具體功能的配置文件,如:db.js
為數(shù)據(jù)庫配置,redis
為 redis 配置。
// db.js
export default {
type: "mysql",
host: "127.0.0.1",
port: "",
name: "",
user: "",
...
};
項(xiàng)目模式的配置,如:env/development.js
,env/testing.js
,env/production.js
//env/development.js
export default {
db: { //開發(fā)模式下數(shù)據(jù)庫配置
type: "mysql",
host: "127.0.0.1",
port: "",
...
}
}
國際化語言包配置,如: locale/en.js
,locale/zh-CN.js
。
配置格式采用 key: value
的形式,并且 key
不區(qū)分大小寫。
框架支持多種級(jí)別的配置文件,會(huì)按以下順序進(jìn)行讀?。?/p>
框架默認(rèn)的配置 -> 項(xiàng)目模式下框架配置 -> 項(xiàng)目公共配置 -> 項(xiàng)目模式下的公共配置 -> 模塊下的配置
在 Controller,Logic,Middleware 等地方可以通過 this.config
來獲取。如:
let db = this.config("db"); //讀取數(shù)據(jù)庫的所有配置
let host = this.config("db.host"); //讀取數(shù)據(jù)庫的 host 配置,等同于 db.host
http 對(duì)象也有 config 方法用來獲取相關(guān)的配置,如:
let db = http.config("db");
其他地方可以通過 think.config
來讀取相關(guān)的配置:
let db = think.config("db"); //讀取通用模塊下的數(shù)據(jù)庫配置
let db1 = think.config("db", undefined, "home"); //獲取 home 模塊下數(shù)據(jù)庫配置
注:
路由解析前,無法通過 config
方法或者 http 對(duì)象上的 config
方法來獲取非通用模塊下的配置,所以路由解析前就使用的配置需要定義在通用模塊里。
項(xiàng)目模式下的配置,config/env/development.js
。
export default {
auto_reload: true,
log_request: true,
gc: {
on: false
},
error: {
detail: true
}
}
config/env/testing.js
和 config/env/produciton.js
無默認(rèn)配置。
國際化語言包配置,默認(rèn)的配置如下:
// config/locale/en.js
export default {
CONTROLLER_NOT_FOUND: "controller `%s` not found. url is `%s`.",
CONTROLLER_INVALID: "controller `%s` is not valid. url is `%s`",
ACTION_NOT_FOUND: "action `%s` not found. url is `%s`",
ACTION_INVALID: "action `%s` is not valid. url is `%s`",
WORKER_DIED: "worker `%d` died, it will auto restart.",
MIDDLEWARE_NOT_FOUND: "middleware `%s` not found",
ADAPTER_NOT_FOUND: "adapter `%s` not found",
GCTYPE_MUST_SET: "instance must have gcType property",
CONFIG_NOT_FUNCTION: "config `%s` is not a function",
CONFIG_NOT_VALID: "config `%s` is not valid",
PATH_EMPTY: "`%s` path muse be set",
PATH_NOT_EXIST: "`%s` is not exist",
TEMPLATE_NOT_EXIST: "can\"t find template file `%s`",
PARAMS_EMPTY: "params `%s` value can\"t empty",
PARAMS_NOT_VALID: "params `{name}` value not valid",
FIELD_KEY_NOT_VALID: "field `%s` in where condition is not valid",
DATA_EMPTY: "data can not be empty",
MISS_WHERE_CONDITION: "miss where condition",
INVALID_WHERE_CONDITION_KEY: "where condition key is not valid",
WHERE_CONDITION_INVALID: "where condition `%s`:`%s` is not valid",
TABLE_NO_COLUMNS: "table `%s` has no columns",
NOT_SUPPORT_TRANSACTION: "table engine is not support transaction",
DATA_MUST_BE_ARRAY: "data is not an array list",
PARAMS_TYPE_INVALID: "params `{name}` type invalid",
DISALLOW_PORT: "proxy on, cannot visit with port",
SERVICE_UNAVAILABLE: "Service Unavailable",
validate_required: "{name} can not be blank",
validate_contains: "{name} need contains {args}",
validate_equals: "{name} need match {args}",
validate_different: "{name} nedd not match {args}",
validate_after: "{name} need a date that\"s after the {args} (defaults to now)",
validate_alpha: "{name} need contains only letters (a-zA-Z)",
validate_alphaDash: "{name} need contains only letters and dashes(a-zA-Z_)",
validate_alphaNumeric: "{name} need contains only letters and numeric(a-zA-Z0-9)",
validate_alphaNumericDash: "{name} need contains only letters, numeric and dash(a-zA-Z0-9_)",
validate_ascii: "{name} need contains ASCII chars only",
validate_base64: "{name} need a valid base64 encoded",
validate_before: "{name} need a date that\"s before the {args} (defaults to now)",
validate_byteLength: "{name} need length (in bytes) falls in {args}",
validate_creditcard: "{name} need a valid credit card",
validate_currency: "{name} need a valid currency amount",
validate_date: "{name} need a date",
validate_decimal: "{name} need a decimal number",
validate_divisibleBy: "{name} need a number that\"s divisible by {args}",
validate_email: "{name} need an email",
validate_fqdn: "{name} need a fully qualified domain name",
validate_float: "{name} need a float in {args}",
validate_fullWidth: "{name} need contains any full-width chars",
validate_halfWidth: "{name} need contains any half-width chars",
validate_hexColor: "{name} need a hexadecimal color",
validate_hex: "{name} need a hexadecimal number",
validate_ip: "{name} need an IP (version 4 or 6)",
validate_ip4: "{name} need an IP (version 4)",
validate_ip6: "{name} need an IP (version 6)",
validate_isbn: "{name} need an ISBN (version 10 or 13)",
validate_isin: "{name} need an ISIN (stock/security identifier)",
validate_iso8601: "{name} need a valid ISO 8601 date",
validate_in: "{name} need in an array of {args}",
validate_notIn: "{name} need not in an array of {args}",
validate_int: "{name} need an integer",
validate_min: "{name} need an integer greater than {args}",
validate_max: "{name} need an integer less than {args}",
validate_length: "{name} need length falls in {args}",
validate_minLength: "{name} need length is max than {args}",
validate_maxLength: "{name} need length is min than {args}",
validate_lowercase: "{name} need is lowercase",
validate_mobile: "{name} need is a mobile phone number",
validate_mongoId: "{name} need is a valid hex-encoded representation of a MongoDB ObjectId",
validate_multibyte: "{name} need contains one or more multibyte chars",
validate_url: "{name} need an URL",
validate_uppercase: "{name} need uppercase",
validate_variableWidth: "{name} need contains a mixture of full and half-width chars",
validate_order: "{name} need a valid sql order string",
validate_field: "{name} need a valid sql field string",
validate_image: "{name} need a valid image file",
validate_startWith: "{name} need start with {args}",
validate_endWidth: "{name} need end with {args}",
validate_string: "{name} need a string",
validate_array: "{name} need an array",
validate_boolean: "{name} need a boolean",
validate_object: "{name} need an object"
}
基本配置,config/config.js
。
export default {
port: 8360, //服務(wù)監(jiān)聽的端口
host: "", //服務(wù)監(jiān)聽的 host
encoding: "utf-8", //項(xiàng)目編碼
pathname_prefix: "", //pathname 去除的前綴,路由解析中使用
pathname_suffix: ".html", //pathname 去除的后綴,路由解析中使用
proxy_on: false, //是否使用 nginx 等 web server 進(jìn)行代理
hook_on: true, //是否開啟 hook
cluster_on: false, //是否開啟 cluster
service_on: true, //Service available
timeout: 120, //120 seconds
auto_reload: false, //自動(dòng)重新加載修改的文件,development 模式下使用
resource_on: true, // 是否處理靜態(tài)資源請(qǐng)求, porxy_on 開啟下可以關(guān)閉該配置
resource_reg: /^(static\/|[^\/]+\.(?!js|html)\w+$)/, //靜態(tài)資源的正則
route_on: true, //是否開啟自定義路由
log_pid: false, //是否記錄服務(wù)的 pid
log_request: false, //是否打印請(qǐng)求的日志
create_server: undefined, //自定義啟動(dòng)服務(wù)
output_content: undefined, //自定義輸出內(nèi)容處理方式,可以進(jìn)行 gzip 處理等
deny_module_list: [], //禁用的模塊列表
default_module: "home", //默認(rèn)模塊
default_controller: "index", //默認(rèn)的控制器
default_action: "index", //默認(rèn)的 Action
callback_name: "callback", //jsonp 請(qǐng)求的 callback 名稱
json_content_type: "application/json", //json 輸出時(shí)設(shè)置的 Content-Type
subdomain: {} //子域名部署配置
}
緩存配置,config/cache.js
。
export default {
type: "file", //緩存方式
prefix: "thinkjs_", //緩存名稱前綴
timeout: 6 * 3600, //6 hours
path: runtimePrefix + "/cache", //文件緩存模式下緩存內(nèi)容存放的目錄
path_depth: 2, //子目錄深度
file_ext: ".json" //緩存文件的擴(kuò)展名
};
cookie 配置,config/cookie.js
。
export default {
domain: "", // cookie domain
path: "/", // cookie path
httponly: false, //是否 httponly
secure: false, //是否在 https 下使用
timeout: 0 //cookie 有效時(shí)間
};
數(shù)據(jù)庫配置,config/db.js
。
export default {
type: "mysql", //數(shù)據(jù)庫類型
host: "127.0.0.1", //數(shù)據(jù)庫 host
port: "", //端口
name: "", //數(shù)據(jù)庫名稱
user: "", //賬號(hào)
pwd: "", //密碼
prefix: "think_", //數(shù)據(jù)表前綴
encoding: "utf8", //數(shù)據(jù)庫編碼
nums_per_page: 10, //一頁默認(rèn)條數(shù)
log_sql: true, //是否記錄 sql 語句
log_connect: true, // 是否記錄連接數(shù)據(jù)庫的信息
cache: { // 查詢數(shù)據(jù)緩存配置
on: true,
type: "",
timeout: 3600
}
};
錯(cuò)誤信息配置,config/error.js
。
export default {
key: "errno", //error number
msg: "errmsg", //error message
value: 1000 //default errno
};
緩存、Session等垃圾處理配置,config/gc.js
。
export default {
on: true, //是否開啟垃圾回收處理
interval: 3600, // 處理時(shí)間間隔,默認(rèn)為一個(gè)小時(shí)
filter: function(){ //如果返回 true,則進(jìn)行垃圾回收處理
let hour = (new Date()).getHours();
if(hour === 4){
return true;
}
}
};
hook 配置,config/hook.js
。
export default {
form_parse: ["parse_json_payload"],
resource_check: ["resource"],
resource_output: ["output_resource"],
route_parse: ["rewrite_pathname", "subdomain_deploy", "route"],
app_begin: ["check_csrf"],
view_init: [],
view_template: ["locate_template"],
view_parse: ["parse_template"],
view_filter: [],
view_end: ["write_html_cache"],
app_end: []
};
post 請(qǐng)求時(shí)的配置,config/post.js
。
export default {
json_content_type: ["application/json"],
max_file_size: 1024 * 1024 * 1024, //1G
max_fields: 100,
max_fields_size: 2 * 1024 * 1024, //2M,
ajax_filename_header: "x-filename",
file_upload_path: runtimePrefix + "/upload",
file_auto_remove: true
};
redis 配置,config/redis.js
。
export default {
host: "127.0.0.1",
port: 6379,
password: "",
timeout: 0,
log_connect: true
};
memcache 配置,config/memcache.js
。
export default {
host: "127.0.0.1", //memcache host
port: 11211,
username: "", //
password: "",
timeout: 0, //緩存失效時(shí)間
log_connect: true
};
session 配置,config/session.js
。
export default {
name: "thinkjs",
type: "file",
path: runtimePrefix + "/session",
secret: "",
auth_key: "think_auth_list",
timeout: 24 * 3600,
cookie: { // cookie options
length: 32
}
};
視圖配置,config/view.js
。
export default {
content_type: "text/html",
file_ext: ".html",
file_depr: "_",
root_path: "",
type: "ejs",
options: {}
};
websocket 配置,config/websocket.js
。
export default {
on: false, //是否開啟 websocket
type: "think", //websocket 使用的庫
allow_origin: "",
sub_protocal: "",
adapter: undefined,
path: "", //url path for websocket
messages: {
// open: "home/websocket/open",
}
};
項(xiàng)目里可以根據(jù)需要擴(kuò)展配置,擴(kuò)展配置只需在 src/common/config/
建立對(duì)應(yīng)的文件即可,如:
// src/common/config/foo.js
export default {
name: "bar"
}
這樣就可以通過 think.config('foo')
來獲取對(duì)應(yīng)的配置了。
更多建議: