primepack
v1.0.7
Published
Full-stack solutions for Node.js and JavaScript.
Downloads
43
Readme
Full-stack solutions for Node.js and JavaScript.
Introducing primepack
- the ultimate solution for developing a robust full-stack application using NodeJS and Javascript. With its advanced features like Fetch, Validation, File Upload, Email, Encryption, and much more, primepack
simplifies the entire development process. Don't let your backend and frontend application lag behind - So, get started on your project with primepack
now!
Fetch
import { Fetch } from "primepack"; // Only Server // Only Client
or
import { Fetch } from "primepack/client"; // Only Client
async function API_Handler(request, response){
const path = "https://www.example.com/api/test"; // The API endpoint URL.
const options = { // Options object are optional
method: "GET", // "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | string - Default: GET.
body: null, // Anything you want to send to the server.
formData: undefined, // Use formData instead of the body when sending "new FormData()".
headers: { // You can customize the headers as per your preference.
"Content-Type": "application/json",
"Accept": "application/json",
... // Add more headers
},
cache: "default", // "force-cache" | "no-cache" | "no-store" | "only-if-cached" | "reload" | "default" - Default: default.
keepalive: false, // boolean - Default: false.
responseObject: false // Set true if you want to get the response object - Default: false.
}
const response = await Fetch(path, options);
console.log(response);
// Output:
{
status: 200, // Response status.
body: object, // Response body.
}
// Note: To get the original response object, set the "responseObject" option to "true".
}
Validation
Sources: validator.
import { Validator } from "primepack"; // Only Server
or
import { Validator } from "primepack/client"; // Only Client
Validator.isEmpty(value: string, options?: validator.IsEmptyOptions) => boolean; // Check if the string has a length of zero.
Validator.isSlug(text: string) => boolean; // Check if the string is of export type slug.
Validator.isEmail(text: string, options?: validator.IsEmailOptions) => boolean; // Check if the string is an email.
Validator.isStrongPassword(text: string, options?: (validator.StrongPasswordOptions & { returnScore?: false })) => boolean; // 1 uppercase and 1 lowercase letter, 1 number and 1 special character.
Validator.isAlpha(text: string, locale?: validator.AlphaLocale, options?: validator.IsAlphaOptions) => boolean; // Check if the string contains only letters (a-zA-Z).
Validator.isNumeric(value: string, options?: validator.IsNumericOptions) => boolean; // Check if the string contains only numbers.
Validator.isAlphanumeric(text: string, locale?: validator.AlphanumericLocale, options?: validator.IsAlphanumericOptions) => boolean; // Check if the string contains only letters and numbers.
Validator.isBoolean(value: string) => boolean; // check if a string is a boolean.
Validator.isFloat(text: string, options?: validator.IsFloatOptions) => boolean; // Check if the string is a float.
Validator.isDecimal(text: string, options?: validator.IsDecimalOptions) => boolean; // Check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0 etc.
Validator.isDate(text: string, options?: validator.IsDateOptions) => boolean; // Check if the string is a valid date.
Validator.isLowercase(text: string) => boolean; // Check if the string is lowercase.
Validator.isUppercase(text: string) => boolean; // Check if the string is uppercase.
Validator.isMobilePhone(value: string, locale?: "any" | validator.MobilePhoneLocale | validator.MobilePhoneLocale[], options?: validator.IsMobilePhoneOptions) => boolean; // Check if the string is a mobile phone number.
Validator.isIMEI(number: string, options?: validator.IsIMEIOptions) => boolean; // Check if the string is a valid IMEI. Non-hyphenated (###############) only is supported by default. Use the options param to enable hyphenated (##-######-######-#) support.
Validator.isBIC(text: string) => boolean; // Check if a string is a BIC (Bank Identification Code) or SWIFT code.
Validator.isCreditCard(number: string, options?: validator.IsCreditCardOptions) => boolean; // Check if the string is a credit card.
Validator.isCurrency(text: string, options?: validator.IsCurrencyOptions) => boolean; // Check if the string is a valid currency amount.
Validator.isJSON(value: string) => boolean; // Check if the string is valid JSON (note: uses JSON.parse).
Validator.isJWT(value: string) => boolean; // Check if the string is valid JWT token.
Validator.isMongoId(text: string) => boolean; //Check if the string is a valid hex-encoded representation of a MongoDB ObjectId.
Validator.isFQDN(value: string, options?: validator.IsFQDNOptions) => boolean; // Check if the string is a fully qualified domain name (e.g. domain.com).
Validator.isIP(value: string, version?: validator.IPVersion) => boolean; // Check if the string is an IP (version 4 or 6).
Validator.isMACAddress(value: string, options?: validator.IsMACAddressOptions) => boolean; // Check if the string is a MAC address.
Validator.isIPRange(value: string, version?: validator.IPVersion) => boolean; // Check if the string is an IP Range (version 4 or 6).
Validator.isPort(value: string) => boolean; // Check if the string is a valid port number.
Validator.isURL(text: string, options?: validator.IsURLOptions) => boolean; // Check if the string is an URL.
Validator.isDataURI(value: string) => boolean; // Check if the string is a data uri format.
Validator.contains(text: string, seed: any, options?: validator.ContainsOptions) => boolean; // Check if the string contains the seed.
Validator.matches(text: string, pattern: RegExp) => boolean; // Check if string matches the pattern.
Validator.equals(text: string, comparison: string) => boolean; // Check if the string matches the comparison.
Validator.isBefore(date: string, comparison?: string) => boolean; // Check if the string is a date that's before the specified date.
Validator.isAfter(date: string, comparison?: string) => boolean; // Check if the string is a date that's after the specified date.
Validator.isDivisibleBy(value: string, number: number) => boolean; // Check if the string is a number that's divisible by another.
Validator.isEAN(value: string) => boolean; // Check if the string is an EAN (European Article Number).
Group Validation
Sources: validator.
import { GroupValidator, Validator } from "primepack"; // Only Server
or
import { GroupValidator, Validator } from "primepack/client"; // Only Client
const validated = GroupValidator([
{
name: "string", // Input field name or any name.
message: "string", // Custom message or leave the field empty.
validate: Validator.isEmpty(""), // Place the validator function that you would like to validate.
},
... // Add more validation
]);
console.log(validated);
Output:
// Valid Output: If all the validations are correct, the output will be an empty array.
[]
// Invalid Output: If any field is invalid, the output will be an array of all invalid fields.
[
{
name: "", // The name you provide.
message: "" // The message you provide.
},
... // More invalid fields
]
Sanitization
Sources: validator.
import { Sanitizer } from "primepack"; // Only Server
or
import { Sanitizer } from "primepack/client"; // Only Client
Sanitizer.toPath(value: string) => string; // Blacklist: `~!@#$%^&*()_+=/*+{[]}|\\;:<>,.? and space replaced with "-"
Sanitizer.toString(value: any) => string; // Convert to string
Sanitizer.toText(value: any) => string; // Convert to a string after removing "`~!@#$%^&*()<>" special characters.
Sanitizer.toNumber(value: any) => number | bigint; // Convert to number
Sanitizer.toBoolean(value: any) => boolean; // Convert to boolean
Sanitizer.blacklist(value: string, chars?: string) => string; // Default : `~!@#$%^&*()<>
Sanitizer.whitelist(value: string, chars: string) => string; // Specify the characters you want to allow
Sanitizer.escape(value: string) => string; // Replace <, >, &, ', " and / with HTML entities.
Sanitizer.trim(value: string, chars?: string) => string; // Trim characters from the left-side of the input.
Sanitizer.ltrim(value: string, chars?: string) => string; // Trim characters from the left-side of the input.
Sanitizer.rtrim(value: string, chars?: string) => string; // Trim characters from the right-side of the input.
Sanitizer.normalizeEmail(email: string) => string; // Convert a string to an email that follows the standard email pattern.
Sanitizer.unescape(value: string) => string; // replace HTML encoded entities with <, >, &, ', " and /.
Sanitizer.slice(value: string, start: number, end?: number) => string; // Get specific text in a string.
Sanitizer.substring(value: string, start: number, end?: number) => string; // Get specific text in a string.
Sanitizer.split(value: string, separator: string | RegExp, limit?: number) => string[]; // Make an array from a string by slicing separator characters.
Sanitizer.replace(value: string, search: string | RegExp, replace: string) => string; // Find and replace in a string.
Sanitizer.replaceAll(value: string, search: string | RegExp, replace: string) => string; // Find and replace all in a string.
JSON Web Token (JWT)
Sources: jsonwebtoken.
import { JWT } from "primepack"; // Only Server
await JWT.encrypt(
payload, // object
secret, // Secret key to encrypt and decrypt jwt. Store the secret key in the .env file.
options: { // Options are optional
algorithm: "HS256", // Default : HS256.
expiresIn: "7d", // string | number - Default : 1 Week.
subject: undefined, // string - Default : undefined.
allowInsecureKeySizes: undefined, // boolean - Default : undefined.
allowInvalidAsymmetricKeyTypes: undefined, // boolean - Default : undefined.
audience: undefined, // string | string[] - Default : undefined.
encoding: undefined, // string - Default : undefined.
header: undefined, // jsonwebtoken.JwtHeader - Default : undefined.
issuer: undefined, // string - Default : undefined.
jwtid: undefined, // string - Default : undefined.
keyid: undefined, // string - Default : undefined.
mutatePayload: undefined, // boolean - Default : undefined.
notBefore: undefined, // string | number - Default : undefined.
noTimestamp: undefined, // boolean - Default : undefined.
},
)
await JWT.decrypt(
token, // string - Encrypted JWT token.
secret, // Secret key to encrypt and decrypt jwt. Store the secret key in the .env file.
)
Encryption
Sources: crypto-js.
import { Encrypt } from "primepack"; // Only Server
await Encrypt.encrypt(text: string, secret: string, algorithm?: "AES" | "Rabbit" | "RC4" | "RC4Drop") => string; // Default algorithm AES
await Encrypt.decrypt(encrypted: string, secret: string, algorithm?: "AES" | "Rabbit" | "RC4" | "RC4Drop") => string; // Default algorithm AES
Hashing
Sources: bcrypt.
import { Hash } from "primepack"; // Only Server
await Hash.make(text: string, rounds?: number) => string; // Default rounds 10
await Hash.compare(text: string, hashed: string) => string;
File Management
Sources: formidable.
import { File } from "primepack"; // Only Server
// Options object are optional
const options {
filename?: string; // custom filename : Default: automatic generated.
extensions?: string[]; // Supported file type. E.G. ["png", "jpg", ...] // Default: all types supported.
maxFiles?: number; // Set a limit on the number of files that can be uploaded at once. // Default: 1 file.
maxFileSize?: number; // Set a maximum size for each file in bytes. // Default: 200 * 1024 * 1024 (200mb)
maxTotalFileSize?: number // Set a maximum size for all files in bytes. // Default: Depends on each file size.
}
await File.upload(
request: Request, // The request object
field: string, // Specify the name of the file parameter.
directory: string, // Provide the folder name where you would like the files to be stored. Note: Start from your project root directory.
options // Options object are optional
);
// Output:
{
success: boolean; // Status of operations.
message: string; // Success or error message.
body: any; // Request body.
errors?: { // Error object: when only there are an or more errors.
directory?: boolean; // When the directory cannot be found.
extensions?: boolean; // When file type does not match with a specific type.
maxFiles?: boolean; // If the files exceeds the maximum files limit.
maxFileSize?: boolean; // If the file size exceeds the maximum file size limit.
maxTotalFileSize?: boolean; // If the all files size exceeds the maximum files size limit.
},
uploads?: [
{ // Uploads object: when only there are all success.
filepath: string; // The file complete path.
filename: string; // The file name.
type: string; // Type of file. E.G. "image/jpg".
size: number // Total size of this file.
},
... // More files.
]
}
// ~ "New feature on version ^1.0.6"
import { File } from "primepack"; // Only Server
await File.delete(filepath: string);
// Output:
{
success: boolean; // Status of operations.
message: string; // Success or error message.
}
Local Storage
import { LocalStorage } from "primepack/client"; // Only Client
LocalStorage.make(name: string, value: string) => boolean;
LocalStorage.find(name: string) => string | null;
LocalStorage.update(name: string, value: string) => boolean;
LocalStorage.remove(name: string) => boolean;
Cookie
Sources: cookie.
import { Cookie } from "primepack"; // Only Server
or;
import { Cookie } from "primepack/client"; // Only Client
// Create Example
function API(request, response) {
// Options object are optional
const options = {
domain: undefined, // string - Default: undefined
encode: undefined, // (value: string) => string - Default: undefined
maxAge: 60 * 60, // number - Default: 1 Hour
expires: undefined, // Date - Default: undefined
httpOnly: true, // boolean - Default: true
partitioned: false, // boolean - Default: false
path: "/", // string - Default: "/"
priority: "Medium", // "Low" | "Medium" | "High" - Default: "Medium"
sameSite: true, // boolean | "lax" | "strict" | "none" - Default: true
secure: true, // boolean - Default: true
};
const makeCookie = Cookie.make("name", "data", options);
response.setHeader("Set-Cookie", makeCookie);
}
// Find Example
function API(request, response) {
// Options object are optional
const options = {
decode: undefined, // (value: string) => string - Default: undefined
};
const findCookie = Cookie.find("name", request.headers["cookie"], options);
console.log(findCookie);
response.end();
}
// FindAll Example
function API(request, response) {
// Options object are optional
const options = {
decode: undefined, // (value: string) => string - Default: undefined
};
const findAllCookie = Cookie.findAll(request.headers["cookie"], options);
console.log(findAllCookie);
// Output: {name: "Value", name2: "Value2", ...} or {}
response.end();
}
// Update Example
function API(request, response) {
// Options object are optional
const options = {
domain: undefined, // string - Default: undefined
encode: undefined, // (value: string) => string - Default: undefined
maxAge: 60 * 60, // number - Default: 1 Hour
expires: undefined, // Date - Default: undefined
httpOnly: true, // boolean - Default: true
partitioned: false, // boolean - Default: false
path: "/", // string - Default: "/"
priority: "Medium", // "Low" | "Medium" | "High" - Default: "Medium"
sameSite: true, // boolean | "lax" | "strict" | "none" - Default: true
secure: true, // boolean - Default: true
};
const updateCookie = Cookie.update("name", "data", options);
response.setHeader("Set-Cookie", updateCookie);
}
// Remove Example
function API(request, response) {
const removeCookie = Cookie.remove("name");
response.setHeader("Set-Cookie", removeCookie);
}
Sources: nodemailer.
import { Mail } from "primepack"; // Only Server
await Mail(
process.env.MAIL_ADDRESS, // Your email address. E.G. [email protected]
"[email protected], [email protected], ...", // Receivers email address.
"Subject", // Subject of E-Mail.
"Body or Template", // Plain text or a HTML template.
process.env.MAIL_HOST, // Your mail server host name. E.G. smtp.gmail.com
process.env.MAIL_PORT, // Your mail server port number. E.G: 136
credentials: {
user: process.env.MAIL_USER, // Your mail server user name
pass: process.env.MAIL_PASS, // Your mail server user password
ssl: true | false // Default: true
}
);
Random Numbers Generator
import { Random } from "primepack"; // Only Server
or;
import { Random } from "primepack/client"; // Only Client
await Random(10); // Generate a random number.
// Output: A5C36F64G6
User Agent
Sources: useragent and request-ip.
import { Agent } from "primepack"; // Only Server
function API(request, response) => {
const userAgent = Agent(request);
console.log(userAgent);
// Output:
{
browser: string; // Users browser with version.
os: string; // Operating system such as Android or iOS with version.
device: string; // Users device such as Mobile or Computer with version.
ip: string // Users IP address, IPv4 or IPv6.
}
}
Version History
v1.0.7
The primepack
has released version 1.0.7
, which doesn't include any new features. Now it's better to modify the core functionality rather than the older primepack
, which is now faster.
v1.0.6
The primepack
has released version 1.0.6
which includes a new feature File.delete()
. For more information, refer to the File Management
documentation.
v1.0.5
The primepack
has released version 1.0.5
which separated server and client actions. Server actions include Fetch Validator GroupValidator Sanitizer Hash Encrypt Cookie Agent Mail JWT Random File
from primepack
, while client actions include Fetch, Validator, GroupValidator, Sanitizer, Cookie, LocalStorage, Random
from primepack/client
.
v1.0.4
The primepack
has released a new version 1.0.4
, with an important update to File Management
. The 1.0.4
version extends the body
field in the file upload response object. To learn more, read the File Management
documentation.
v1.0.3
(Stable)
The version 1.0.3
is stable, which means that the primepack
1.0.3
is now ready for your project!