Skip to content

Instantly share code, notes, and snippets.

@Niakr1s
Created January 29, 2021 10:36
Show Gist options
  • Save Niakr1s/f037d0ac06d75004a356e4af70cd06d0 to your computer and use it in GitHub Desktop.
Save Niakr1s/f037d0ac06d75004a356e4af70cd06d0 to your computer and use it in GitHub Desktop.
import { IsString, validateOrReject } from 'class-validator'
interface ICommandPackage {
kind: 'commandPackage'
command: string
}
interface IMessagePackage {
kind: 'messagePackage'
message: string
}
type IPackage = ICommandPackage | IMessagePackage
async function newPackageFromDTO(object: any): Promise<IPackage> {
let res: IPackage
switch (object.kind as IPackage["kind"]) {
case 'commandPackage':
res = new CommandPackage({ ...object })
break;
case 'messagePackage':
res = new MessagePackage({ ...object })
break
default:
throw new Error(`invalid kind: ${object.kind}`)
}
try {
await validateOrReject(res)
return res
} catch (e) {
throw e
}
}
class CommandPackage implements ICommandPackage {
kind: 'commandPackage' = 'commandPackage';
@IsString()
command: string;
constructor({ command }: { command: string }) {
this.command = command
}
}
class MessagePackage implements IMessagePackage {
kind: 'messagePackage' = 'messagePackage';
@IsString()
message: string;
constructor({ message }: { message: string }) {
this.message = message
}
}
async function test() {
let commandPackageDTO = {
valid: {
kind: 'commandPackage',
command: 'go',
},
invalid: {
kind: 'commandPackage',
Command: 'go',
}
}
let messagePackageDTO = {
valid: {
kind: 'messagePackage',
message: 'yoyoyo',
},
invalid: {
kind: 'messagePackage',
messageee: 'yoyoyo',
}
}
let invalidPackageDTO = {
kind: 'lol',
command: 'go',
}
async function test(name: string, dto: any) {
try {
let instance = await newPackageFromDTO(dto)
console.log(name, instance)
} catch (e) {
console.error(name, 'invalid')
}
}
test('commandPackageDTO.valid', commandPackageDTO.valid)
test('commandPackageDTO.invalid', commandPackageDTO.invalid)
test('messagePackageDTO.valid', messagePackageDTO.valid)
test('messagePackageDTO.invalid', messagePackageDTO.invalid)
test('invalidPackageDTO', invalidPackageDTO)
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment