Frame built-in global object think
, easy to use in the project anytime, anywhere.
think.app
is an instance of Koa Application object, generated at system startup.
In addition, more attributes have been extended for the app.
think.app.think
is equivalent to the think object. Make it easy to use other methods on the think object where the app object is passed in.think.app.modules
list of modules, empty array in single module projectthink.app.controllers
save the controller file in the project, for quick follow-up callthink.app.logics
stores logic files in the projectthink.app.models
stores model files in the projectthink.app.services
stores service filesthink.app.routers
stores custom router configurationthink.app.validators
stores calibration configurationthink.app.server
the server object after creating the HTTP serviceIf you want to check the value of these properties, you can do it in the appReady
event.
think.app.on('appReady', () => {
console.log(think.app.controllers)
})
The root directory of the project, other directories can be generated through this, such as:
const runtimePath = path.join(think.ROOT_PATH, 'runtime/');
const viewPath = path.join(think.ROOT_PATH, 'view/');
APP root directory, the default is ${think.ROOT_PATH}/app
. If the project doesn't need to translate, the default path is: ${think.ROOT_PATH}/src
.
The current runtime, equivalent to think.app.env
, is defined in the portal file like development.js
.
The current ThinkJS version number.
name
{String} key to be configuredvalue
{Mixed} value to be configuredm
{String} module name, used in multi-module projectRead or set the configuration, this function is implemented by the think-config module. In the context, controller, logic can be directly through the this.config
method to operate the configuration.
// get configuration
const value1 = think.config('name');
// get the specified module configuration, valid in multi-module project
const value2 = think.config('name', undefined, 'admin');
// set configuration
think.config('name', 'value');
// specify the module setting configuration value
think.config('name', 'value', 'admin');
Controller base class, other controller classes inherit this class.
// src/controller/user.js
module.exports = class userController extends think.Controller {
indexAction() {
}
}
Logic base class, inherited from think.Controller
.
// src/logic/user.js
module.exports = class userLogic extends think.Logic {
indexAction() {
}
}
Service base class, other service classes inherit this class.
// src/service/sms.js
module.exports = class extends think.Service {
}
name
{String} Service namem
{String} module name, valid in multi-module project...args
{Array} instantiate the required parameters for the Service class. In the single-module project, the m
parameter is supplemented with args.Instantiate the Service class, if the exported object is not a class, then return directly.
const instance1 = think.service('sms');
const instance2 = think.service('sms', 'admin');
fn
{Function} function name to registerFunctions registered and executed before the service is started, fn needs to return Promise if there is an asynchronous operation.
array
{any} determine whether the input is an arrayreturn
{Boolean}Determine whether it is an array, equivalent to Array.isArray
.
think.isArray([]); // true
think.isArray({}); // false
boolean
{any}Determine whether the input is a Boolean value
think.isBoolean(false); // true
any
{any}Determine whether the input is an integer.
any
{any}Determine the input is null
, you can also directly determine the xxx == null
.
any
{any}Determine the input is null
or undefined
.
number
{any}Determine whether the input is a number.
think.isNumber(1); // true
str
{any}Determine whether the input is String.
any
{any}Determine whether the type of input is Symbol.
any
{any}Determine whether the input is undefined, you can also directly determine the xxx == undefined
.
reg
{any}Determine whether the input is a RegExp object.
date
{any}Judge whether the input is a Date object.
error
{any}Determining whether the type of input is Error.
any
{any}Determine whether the type of input is Function.
any
{any}Determine whether the input is of primitive type, including: null
, string
, boolean
, number
, symbol
, undefined
.
ip
{String}Determine whether a string is ip address, IP v4 or IP v6, equivalent to net.isIP
.
buffer
{any}Determine whether the input is a Buffer object, equivalent to Buffer.isBuffer
.
ip
{String}Determine whether a string is an IP v4 address, equivalent to net.isIPv4
.
ip
{String}Determine whether a string is an IP v6 address, equivalent to net.isIPv6
.
Determine whether the current process is the main process, equivalent to cluster.isMaster
.
obj
{any}Determine whether an input is an Object, by Object.prototype.toString.call(obj)
is [Object Object]
to determine.
think.isObject({}); // true
think.isObject([]); // false
think.isObject(null); // false
fn
{Function} function will be wrappedreceiver
{Object} the object will be boundThis method wraps a callback function as Promise.
let fn = think.promisify(fs.readFile, fs);
let data = await fn(__filename);
target
{Object} to extend the target object...any
{Object} there can be any number of objectsDeep copy of the object, if the key is the same, then the value will be overwritten with the previous value.
think.extend({a: 1}, {b: 2});
// return {a:1,b:2};
think.extend({a: 1}, {a: 2});
// return {a: 2}
str
{String}Turn snake case into camel case.
think.camelCase('index_index');
// return 'indexIndex'
str
{String}Turn camel case into snake case.
think.snakeCase('indexIndex');
// return 'index_index'
str
{String}Determine whether the input is a string type of number.
think.isNumberString('419');
// return true
any
{any}Determine whether the real empty, undefined
, null
, ''
, NaN
is true, the other is false.
think.isTrueEmpty(null);
// return true
any
{any}Determine whether the object is empty, undefined
, null
,''
, NaN
, []
, {}
, 0
, false
is true, the other is false.
think.isEmpty(null);
// return true
Generate a Deferred object.
function test() {
const defer = think.defer();
setTimeout(function() {
defer.reslove('1');
},1000)
return defer
}
test().then((result)=>{
resut === '1'
})
obj
{Object} the object to manipulateprops
{String | Array} attributes to ignore, if a string, separate multiple values with commasIgnore some of the properties in the object and return a new object.
const value = think.omit({a: 1, b: 2, c: 3}, 'a,b');
// value is {c: 3}
str
{String}Calculates the md5 value of the string.
num
{Number} time, in millisecondsPackage setTimeout as Promise.
think.timeout(1000).then(()=>{
...
})
str
{String}Escape the string of HTML, escape <
、>
、"
、'
characters.
data
{Date}format
{String} default 'YYYY-MM-DD HH:mm:ss'Return a formatted date.
think.datetime(1501406894849)
// return "2017-07-30 17:28:14"
version
{String} v1|v4return
{String}Generate uuid strings, conforming to RFC4122 specifications, based on uuid module.
str
{String}return
{Number}把一个语义化的时间转成毫秒,如果转换失败则抛异常,使用 ms 库转换。 Turn a semantic time into milliseconds, throw an exception if the conversion fails, and use the ms library conversion.
think.ms('2 days') // 1d,10h,1y
// return 172800000
path
{String}Check whether the path exists.
think.isExist('/usr/local/bin/node')
// return true
filepath
{String}Check if it is a file path.
think.isFile('/usr/local/bin/node')
// return true
filepath
{String}Check if it is a folder path.
think.isDirectory('/usr/local/bin')
// return true
path
{String}mode
{String} default '0777'Change the permissions of a file or folder.
think.chmod('/usr/local/bin', '0775')
path
{String} the directory to createmode
{String} folder permissions, the default is 0777
return
{Boolean}Create a folder. Return true if created successfully, false otherwise.
think.mkdir('/usr/local/bin/thinkjs', '0775')
dir
{String} folder pathprefix
{String} path prefixreturn
{Array} an array containing all filesGet all the files under the folder.
think.getdirFiles('/usr/local/bin')
// return []
path
{String}reserve
{Boolean} whether to retain the current folder, delete only the files under the folderDelete folders and folders under the file, asynchronous operation.
think.rmdir('/usr/local/bin/thinkjs', true).then(()=>{
console.log('Delete completed.')
})
It is not recommended to use the think object directly in the middleware, adapter, extend, which will make the plug-in code inconvenient for unit testing. If you want to use the app
object can be passed in, and then use the app.think.xxx
attributes or methods on the think object.
// src/config/middleware.js
module.exports = [
{
handle: xxx
}
];
// xxx middleware
module.exports = (options, app) => {
return (ctx, next) => {
// get the list of modules for the project via app.think.modules
const modules = app.think.modules;
// If it is a multi-module project (single-module project length is always 0)
if(modules.length) {
}
}
}