@trongtindev/nodecore v0.0.4
Disclaimer
- ⚠️ Expect bugs and breaking changes.
- ⚠️ The project is under very active development.
Features
| Features | Status |
|---|---|
core Route | Working |
core Controllers | Working |
core Middleware | OK |
core Hook | |
core Static assets | OK |
plugin Multipart: Process uploading native file or base64 file. | |
plugin Uploader: Direct file uploads local, cloud like S3. | |
plugin Cache: Support file, redis, memcached, using native Cache.redis(). | Working |
plugin Database: Support mysql, mongodb, using native Database.mongodb(). | Working |
plugin Authentication | Working |
prototypes more native support for Number, String, Array, Object,... | OK |
Table of contents
About
Usage
See example folder.
Core
Http
https://www.npmjs.com/package/express
Logger
Request
- Promise based HTTP client for the browser and node.js https://www.npmjs.com/package/axios
import {Logger, Request} from '@trongtindev/nodecore';
Logger.info('requesting...');
Request.get('http://localhost', {
timeout: 10000,
})
.then((res) => Logger.info(res.statusText))
.catch((error) => Logger.error(error.toString()));Plugins
Auth
import Application, {Auth, AuthConfig} from '@trongtindev/nodecore';
const accessToken = await Auth.sign({
aud: 'user id',
iss: 'local',
claims: {
name: 'user name',
email: 'uer email',
},
});
const refreshToken = await Auth.sign({
aud: userId.toString(),
iss: 'local',
claims: {
userAgent: 'user-agent',
},
}, {
expiresIn: '30d',
});Cache
Redis
https://www.npmjs.com/package/redis
import Application, {Cache, CacheConfig} from '@trongtindev/nodecore';
Cache.redis().get('users');
Cache.redis('myredis').get('users');Database
Mongodb
https://www.npmjs.com/package/mongodb
import Application, {Datababse, DatabaseConfig} from '@trongtindev/nodecore';
Datababse.mongodb().collection('users');
Datababse.mongodb('mymongodb').collection('users');Uploader
Authentication
Prototypes
✅ No need import anything! Ready to use.
Number
prettyBytes
Convert bytes value to a human-readable string. For options, reference the bytes https://www.npmjs.com/package/bytes.
1024.
prettyBytes(); // 1KB
1024.
prettyBytes({unitSeparator: ' '}); // 1 KBprettyMs
Convert bytes value to a human-readable string. For options, reference the bytes https://www.npmjs.com/package/bytes.
60000.
prettyMs(); // 1min
60000.
prettyMs({long: true}); // 1 minute
60000.
prettyMs({long: true, locale: 'vi'}); // 1 phútString
capitalCase
Capitalize a string
'helloWorld'.capitalCase(); // StringcamelCase
Convert a string to its camelCase version.
'hello-world'.camelCase(); // helloWorldsnakeCase
Convert a string to its snake_case version.
'helloWorld'.snakeCase(); // hello_worlddashCase
Convert a string to its dash-case version. Optionally, you can also capitalize the first letter of each segment.
'helloWorld'.dashCase(); // hello-worldpascalCase
Convert a string to its PascalCase version.
'helloWorld'.pascalCase(); // HelloWorldsentenceCase
Convert string to a sentence
'hello-world'.sentenceCase(); // Hello worldnoCase
Remove all sorts of casing
'hello-world'.noCase(); // Hello world
'hello-world'.noCase(); // hello world
'hello_world'.noCase(); // hello world
'helloWorld'.noCase(); // hello worldtitleCase
Convert a sentence to title case
'Here is a fox'.titleCase(); // Here Is a Foxdecode
- Default is
json
const str: string = '{"key":"value"}';
str.decode();
// {key:"value"}const str: string = 'eyJrZXkiOiJ2YWx1ZSJ9';
str.decode('base64');
// {"key":"value"}encode
const str: string = '{"key":"value"}';
str.encode('base64');
// eyJrZXkiOiJ2YWx1ZSJ9truncate
Truncate a string after a given number of characters
'This is a very long, maybe not that long title'.truncate(12);
// This is a ve...By default, the string is truncated exactly after the given characters. However, you can instruct the method to wait for the words to complete.
'This is a very long, maybe not that long title'.truncate(12, {
completeWords: true,
});
// This is a very...Also, it is possible to customize the suffix.
'This is a very long, maybe not that long title'.truncate(12, {
completeWords: true,
suffix: ' <a href="/1"> Read more </a>',
});
// This is a very <a href="/1"> Read more </a>excerpt
The method is the same as the method. However, it strips the HTML from the String.truncate
'<p>This is a <strong>very long</strong>, maybe not that long title</p>'.excerpt(
12,
{
completeWords: true,
}
);
// This is a very...condenseWhitespace
Condense whitespaces from a given string. The method removes the whitespace from the , , and
multiple whitespaces
between the words. left and right
' hello world '.condenseWhitespace();
// "hello world"escapeHTML
Escape HTML from the string
'<p> foo © bar </p>'.escapeHTML();
// <p> foo © bar </p>toSlugCase
Convert string to slug
'this is title'.toSlugCase();
// this-is-titleAdditionally, you can also encode non-ASCII symbols.
'<p> foo © bar </p>'.escapeHTML({
encodeSymbols: true,
});
// <p> foo © bar </p>encodeSymbols
Encode symbols. Checkout he for available options
'foo © bar'.encodeSymbols();
// foo © bartoBytes
Convert human-readable string to bytes. This method is the opposite of the
method Number.prettyBytes
'1KB'.toBytes();
// 1024toMs
Convert human-readable string to milliseconds. This method is the opposite of the
method Number.prettyMs
'1min'.toMs();
// 60000
'1 minute'.toMs({long: true});
// 60000
'1 phút'.toMs({long: true, locale: 'vi'});
// 60000generateRandom
- Generate a cryptographically strong random string.
- @length default is
10
const str: string = 'abcd';
str.generateRandom();
// bdccadcbaa
str.generateRandom(10);
// abdaaadbaadacccbcdcbisEmpty
Find if a value is empty. Also checks for empty strings with all whitespace
''.isEmpty(10);
// true
' '.generateRandom(10);
//trueisCuid
Validation a collision-resistant ID. This method is the opposite of the method String.cuid
'not a cuid'.isCuid();
// false
'tz4a98xxat96iws9zmbrgj3a'.isCuid();
// trueisObjectId
'not a object id'.isObjectId();
// false
'64cfba9e73e3aaae57e53069'.isObjectId();
// trueArray
const arr = ['a', 'b', 'c'];
arr.contains('a');
// true
arr.contains(['a', 'd']);
// true
arr.contains(['a', 'd'], {condition: 'AND'});
// falseconst arr = ['a', 'b', 'c'];
arr.first();
// a
arr.firstOrNull();
// a | nullconst arr = ['a', 'b', 'c'];
arr.last();
// c
arr.lastOrNull();
// c | nullconst arr = ['a', 'b', 'c'];
arr.remove('a');
// arr or return [b, c]
arr.remove(['a', 'b']);
// arr or return [c]
arr.removeAt(0);
// arr or return [b, c]
arr.removeAt([1, 2]);
// arr or return [c]Object
Object encode
- Default is
json
const obj: object = {key: 'value'};
obj.encode();
// {"key":"value"}
obj.encode('base64');
// eyJrZXkiOiJ2YWx1ZSJ9Global
✅ No need import anything! Ready to use.
cuid
Generate a collision-resistant ID https://github.com/paralleldrive/cuid2
cuid();
// tz4a98xxat96iws9zmbrgj3a
cuid({length: 10});
// wjfazn7qnd
cuid({
// A custom random function with the same API as Math.random.
// You can use this to pass a cryptographically secure random function.
random: Math.random,
// the length of the id
length: 10,
// A custom fingerprint for the host environment. This is used to help
// prevent collisions when generating ids in a distributed system.
fingerprint: 'a-custom-host-fingerprint',
});
// wjfazn7qndgenerateRandom
- Generate a cryptographically strong random string.
- Like
String.generateRandombut with system characters.
generateRandom();
// lMzPhsu4CF
generateRandom(10);
// cV2AE8sXsacAAf4qUqUO