Created
April 4, 2021 08:49
-
-
Save AliN11/41e5020c2fab7e98811ea85118242c8e to your computer and use it in GitHub Desktop.
Builder Design Pattern with Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface QueryBuilder { | |
table(table): QueryBuilder; | |
select(cols): QueryBuilder; | |
limit(value: Number): QueryBuilder; | |
where(col, value): QueryBuilder; | |
getQuery(): String; | |
/* +100 Other SQL Methods */ | |
} | |
class MySqlQueryBuilder implements QueryBuilder { | |
private query: String; | |
private tableName: String; | |
public constructor() { | |
this.query = ''; | |
} | |
public table(table): QueryBuilder { | |
this.tableName = table; | |
return this; | |
} | |
public select(cols): QueryBuilder { | |
/** ... */ | |
return this; | |
} | |
public limit(value: Number): QueryBuilder { | |
/** ... */ | |
return this; | |
} | |
public where(col, value): QueryBuilder { | |
/** ... */ | |
return this; | |
} | |
public getQuery(): String { | |
return 'This is a MySQL query'; | |
} | |
} | |
class MongoDbQueryBuilder implements QueryBuilder { | |
private query: String; | |
private tableName: String; | |
public constructor() { | |
this.query = ''; | |
} | |
public table(table): QueryBuilder { | |
this.tableName = table; | |
return this; | |
} | |
public select(cols): QueryBuilder { | |
/** ... */ | |
return this; | |
} | |
public limit(value: Number): QueryBuilder { | |
/** ... */ | |
return this; | |
} | |
public where(col, value): QueryBuilder { | |
/** ... */ | |
return this; | |
} | |
public getQuery(): String { | |
return 'This is a MongoDB query'; | |
} | |
} | |
function client(builder: QueryBuilder) { | |
const query = builder.table('posts').where('id', 429).limit(10).select(['id', 'title']).getQuery(); | |
console.log(query); | |
} | |
const config = { | |
database1: MongoDbQueryBuilder, | |
database2: MySqlQueryBuilder | |
} | |
client(new config.database1); // This is a MongoDB query | |
client(new config.database2); // This is a MySQL query |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment