feat: add encryption and date service utilities
- Implemented EncryptionService for secure data handling with AES encryption. - Created DateService for advanced date manipulation and formatting. - Developed EncryptionDemo and DateServiceComponent for interactive demonstrations. - Added LocalStorage demo for encrypted data storage and retrieval. - Established ESLint and TypeScript configurations for utils package. - Included example utility function for demonstration purposes.
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import dayjs, { Dayjs, OpUnitType, ManipulateType } from 'dayjs';
|
||||
|
||||
/**
|
||||
* FIX: Tambahkan 'Dayjs' ke dalam union type ini.
|
||||
* Ini memberitahu TS bahwa input boleh berupa string, date, atau object Dayjs itu sendiri.
|
||||
*/
|
||||
export type DateInput = string | number | Date | Dayjs | null | undefined;
|
||||
|
||||
export type TimeUnit = 'day' | 'week' | 'month' | 'year' | 'hour' | 'minute' | 'second';
|
||||
|
||||
interface IDateManager {
|
||||
format(formatString?: string): string;
|
||||
add(value: number, unit: TimeUnit): IDateManager;
|
||||
subtract(value: number, unit: TimeUnit): IDateManager;
|
||||
|
||||
// Update: Parameter sekarang support DateService instance juga (untuk DX lebih baik)
|
||||
isBefore(date: DateInput | DateService): boolean;
|
||||
isAfter(date: DateInput | DateService): boolean;
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean;
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise?: boolean): number;
|
||||
|
||||
toISOString(): string;
|
||||
toDate(): Date;
|
||||
startOf(unit: TimeUnit): IDateManager;
|
||||
endOf(unit: TimeUnit): IDateManager;
|
||||
}
|
||||
|
||||
export class DateService implements IDateManager {
|
||||
// Kita expose _date sebagai public readonly atau getter jika perlu akses raw dayjs
|
||||
// Tapi untuk strict encapsulation, keep private.
|
||||
private readonly _date: Dayjs;
|
||||
|
||||
constructor(date?: DateInput | DateService) {
|
||||
// FIX: Handle jika inputnya adalah instance dari DateService lain
|
||||
if (date instanceof DateService) {
|
||||
this._date = date.getRaw();
|
||||
} else {
|
||||
this._date = dayjs(date);
|
||||
}
|
||||
|
||||
if (!this._date.isValid()) {
|
||||
console.warn(`[DateService] Invalid date: ${date}. Fallback to now.`);
|
||||
this._date = dayjs();
|
||||
}
|
||||
}
|
||||
|
||||
// Helper internal untuk mengambil raw object (diperlukan untuk interaksi antar instance)
|
||||
public getRaw(): Dayjs {
|
||||
return this._date;
|
||||
}
|
||||
|
||||
static now(): DateService {
|
||||
return new DateService();
|
||||
}
|
||||
|
||||
// --- Implementation Methods ---
|
||||
|
||||
format(formatString: string = 'YYYY-MM-DD'): string {
|
||||
return this._date.format(formatString);
|
||||
}
|
||||
|
||||
add(value: number, unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.add(value, unit as ManipulateType));
|
||||
}
|
||||
|
||||
subtract(value: number, unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.subtract(value, unit as ManipulateType));
|
||||
}
|
||||
|
||||
// Helper private untuk normalisasi input (menangani DateService vs DateInput biasa)
|
||||
private _toDayjs(date: DateInput | DateService): Dayjs {
|
||||
if (date instanceof DateService) {
|
||||
return date.getRaw();
|
||||
}
|
||||
return dayjs(date);
|
||||
}
|
||||
|
||||
isBefore(date: DateInput | DateService): boolean {
|
||||
return this._date.isBefore(this._toDayjs(date));
|
||||
}
|
||||
|
||||
isAfter(date: DateInput | DateService): boolean {
|
||||
return this._date.isAfter(this._toDayjs(date));
|
||||
}
|
||||
|
||||
isSame(date: DateInput | DateService, unit?: TimeUnit): boolean {
|
||||
return this._date.isSame(this._toDayjs(date), unit as OpUnitType);
|
||||
}
|
||||
|
||||
diff(date: DateInput | DateService, unit: TimeUnit, precise: boolean = false): number {
|
||||
return this._date.diff(this._toDayjs(date), unit as OpUnitType, precise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Menghitung selisih HARI KALENDER.
|
||||
* Mengabaikan jam/menit, murni membandingkan tanggal.
|
||||
*/
|
||||
diffCalendarDay(date: DateInput | DateService): number {
|
||||
const target = this._toDayjs(date);
|
||||
// Reset keduanya ke jam 00:00:00 sebelum diff
|
||||
return this._date.startOf('day').diff(target.startOf('day'), 'day');
|
||||
}
|
||||
|
||||
startOf(unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.startOf(unit as OpUnitType));
|
||||
}
|
||||
|
||||
endOf(unit: TimeUnit): DateService {
|
||||
return new DateService(this._date.endOf(unit as OpUnitType));
|
||||
}
|
||||
|
||||
toISOString(): string {
|
||||
return this._date.toISOString();
|
||||
}
|
||||
|
||||
toDate(): Date {
|
||||
return this._date.toDate();
|
||||
}
|
||||
|
||||
get timestamp(): number {
|
||||
return this._date.valueOf();
|
||||
}
|
||||
|
||||
/* Mengembalikan Epoch dalam Milliseconds (13 digit).
|
||||
* Contoh: 1704067200000
|
||||
* Gunakan ini untuk kalkulasi di Frontend JS/TS.
|
||||
*/
|
||||
get epochMillis(): number {
|
||||
return this._date.valueOf();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengembalikan Epoch dalam Seconds (10 digit).
|
||||
* Contoh: 1704067200
|
||||
* Gunakan ini untuk kirim ke Backend (PHP, Golang, Python, dll) atau JWT.
|
||||
*/
|
||||
get epochSeconds(): number {
|
||||
return this._date.unix();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const ENC_STORAGE_KEY = 'zkwqyo3RpNEh8un2CIAs'; //TODO change value from environment
|
||||
@@ -0,0 +1,70 @@
|
||||
import { AES, enc } from 'crypto-js';
|
||||
import { ENC_STORAGE_KEY } from './encryption-key';
|
||||
|
||||
/**
|
||||
* Interface contract supaya method konsisten
|
||||
*/
|
||||
interface IEncryptionService {
|
||||
encrypt(data: string): string;
|
||||
decrypt(encryptedData: string): string;
|
||||
}
|
||||
|
||||
export class EncryptionService implements IEncryptionService {
|
||||
private readonly _key: string;
|
||||
|
||||
/**
|
||||
* @param key (Optional) Jika tidak diisi, otomatis pakai ENC_STORAGE_KEY
|
||||
*/
|
||||
constructor(key: string = ENC_STORAGE_KEY) {
|
||||
if (!key) {
|
||||
throw new Error('[EncryptionService] Encryption key is missing/empty.');
|
||||
}
|
||||
this._key = key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengenkripsi string plain text.
|
||||
*/
|
||||
public encrypt(data: string): string {
|
||||
if (!data) {
|
||||
return '';
|
||||
}
|
||||
return AES.encrypt(data, this._key).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mendekripsi string terenkripsi.
|
||||
* Mengembalikan string kosong '' jika gagal decrypt atau format salah.
|
||||
*/
|
||||
public decrypt(encryptedData: string): string {
|
||||
if (!encryptedData) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
const bytes = AES.decrypt(encryptedData, this._key);
|
||||
const originalText = bytes.toString(enc.Utf8);
|
||||
|
||||
// Validasi tambahan: jika hasil decrypt kosong, berarti key salah atau data corrupt
|
||||
if (!originalText) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return originalText;
|
||||
} catch (error) {
|
||||
console.error('[EncryptionService] Decryption failed:', error);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// --- Static Helper (Singleton Pattern sederhana) ---
|
||||
// Supaya tidak perlu 'new EncryptionService()' berulang kali
|
||||
private static instance: EncryptionService;
|
||||
|
||||
public static getInstance(): EncryptionService {
|
||||
if (!EncryptionService.instance) {
|
||||
EncryptionService.instance = new EncryptionService();
|
||||
}
|
||||
return EncryptionService.instance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function utilsExample() {
|
||||
return 'This is an example utility function.';
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from './encryption';
|
||||
export * from './example';
|
||||
export * from './date-service';
|
||||
Reference in New Issue
Block a user