@active-record-ts/active-model
v1.1.0
Published
Rails-style ActiveModel for TypeScript — typed attributes, dirty tracking, validations, callbacks.
Readme
@active-record-ts/active-model
Typed attributes, dirty tracking, validations, and callbacks for plain TypeScript classes — no database. A port of Rails' ActiveModel.
Used by @active-record-ts/active-record for persistence; usable on its own for form objects, API payloads, etc.
Usage
import { Model } from '@active-record-ts/active-model';
class Signup extends Model {
declare email: string;
declare age: number;
}
Signup.attribute('email', 'string');
Signup.attribute('age', 'integer');
Signup.validates('email', { presence: true, format: { with: /@/ } });
Signup.validates('age', { numericality: { greaterThanOrEqualTo: 13 } });
const s = new Signup({ email: '[email protected]', age: 12 });
await s.validate(); // false
s.errors.fullMessages; // ["Age must be greater than or equal to 13"]Features
- Typed attributes —
attribute(name, type). Built-ins:string,integer,bigint,float,decimal,boolean,date,datetime,binary,json. Register your own withregisterType. - Dirty tracking —
record.changed(),record.changes(),record.wasChanged(attr),record.savedChanges(). - Validations —
presence,absence,format,length,numericality,inclusion,exclusion,acceptance,confirmation. - Callbacks —
beforeValidation,afterValidation,beforeSave,afterSave,aroundSave. ThrowHaltError(or callthrowAbort()) inside abefore*callback to halt the chain. - Errors —
record.errorsexposes Rails-styleadd,on,fullMessages, etc. - Inflector —
camelize,underscore,pluralize,tableize.
Test
bun run test:active-model