vaughan
vaughan

Reputation: 7475

Using Typescript to map database schemas

I have a legacy database which I want to expose over a fresh new API.

I need to map the field names of the models from the legacy db to my new model classes.

I want to do this in a type-safe way instead of using just a dictionary of string mappings which are prone to errors.

// The new model.
class Patient {
  firstName: string
  lastName: string
  dateOfBirth: Date
}

var p: Patient;

legacyToNewModelMappings =
  "First Name": p.firstName
  "Family Name": p.familyName
  "DOB": p.dateOfBirth

This is nice because if I change a field in my new model, refactoring will be easy and I will get an alert in my IDE if there is an issue.

However I need to be able to map back and forth between the two models. Using references though means I can't map from the legacy DB to the new DB.

I am using TypeScript in Node.js.

Any other approaches I should be looking at?

Upvotes: 1

Views: 2273

Answers (1)

thoughtrepo
thoughtrepo

Reputation: 8383

I'm trying to understand what you try to accomplish here, so please correct me if I'm wrong.

Couldn't you use getters and setters on one model to match the properties of field names for both databases?

class Patient {
    public firstName: string;
    public lastName: string;
    public dateOfBirth: Date;

    get "First Name" (): string {
        return this.firstName;
    }
    get "Family Name" (): string {
        return this.familyName;
    }
    get "DOB" (): Date {
        return this.dateOfBirth;
    }

    set "First Name" (value: string) {
        this.firstName = value;
    }
    set "Family Name" (value: string) {
        this.familyName = value;
    }
    set "DOB" (value: Date) {
        this.dateOfBirth = value;
    }
}

Upvotes: 1

Related Questions