Skip to content

Instantly share code, notes, and snippets.

@rossnelson
Last active January 18, 2024 19:48
Show Gist options
  • Save rossnelson/17f8c3deb5979464cf81c1cb0cf96b93 to your computer and use it in GitHub Desktop.
Save rossnelson/17f8c3deb5979464cf81c1cb0cf96b93 to your computer and use it in GitHub Desktop.
Proxy model allowing helpers tied to data objects
import _ from 'lodash';
import { DateTime } from 'luxon';
import moment from 'moment-timezone';
class Base<T> {
params: T;
constructor(params: T) {
this.params = params;
}
get id() {
return this.params.id;
}
get category() {
return this.constructor.category;
}
get type() {
return this.constructor.type;
}
get pluralType() {
return this.constructor.pluralType;
}
static get listURL() {
return '/' + _.compact([this.category, this.pluralType]).join('/');
}
static get creatorURL() {
return (
'/' + _.compact([this.category, this.pluralType, 'create']).join('/')
);
}
static editorURL(id: string) {
return (
'/' + _.compact([this.category, this.pluralType, id, 'edit']).join('/')
);
}
get editorURL() {
return (
'/' +
_.compact([this.category, this.pluralType, this.id, 'edit']).join('/')
);
}
get expiresAt() {
const { expiration_date } = this.params;
if (!expiration_date) return '';
return moment(expiration_date).tz(moment.tz.guess()).fromNow();
}
get createdAt() {
const { created_at: createdAt } = this.params;
return createdAt ? DateTime.fromSeconds(createdAt) : undefined;
}
get updatedAt() {
const { updated_at: updatedAt } = this.params;
return updatedAt ? DateTime.fromSeconds(updatedAt) : undefined;
}
get lastTimestamp() {
return !this.updatedAt ? this.createdAt : this.updatedAt;
}
patch(properties: Partial<T>) {
this.params = { ...this.params, ...properties };
}
toJSON() {
return this.params;
}
}
var proxyHandler = {
get: function <T>(obj: Base<T>, name: keyof T) {
return _.isNil(obj.params[name]) ? obj[name] : obj.params[name];
},
set: function <T>(obj: Base<T>, name: keyof T, value: any) {
obj.params[name] = value;
return true;
},
};
export default Base;
import Base from './base-model'; // Assuming 'Base' is in the same directory
interface MyObjectParams {
id: number;
name: string;
expiration_date: string;
// Add other properties as needed
customer: {
name: "Ross Nelson"
}
}
class MyObject extends Base<MyObjectParams> {
// You can add additional methods or properties specific to MyObject here
get customerName() {
return this.params.customer.name
}
}
const params: MyObjectParams = {
id: 1,
name: 'Example',
expiration_date: '2024-01-31',
};
const myInstance = new MyObject(params);
console.log(myInstance.id); // Accessing the 'id' property
console.log(myInstance.expiresAt); // Accessing the 'expiresAt' method
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment