11import { entities , DataSource } from "@repo/indexer-database" ;
2+ import { exists } from "../utils" ;
23import assert from "assert" ;
34
45// This class is intended to store integration clients allowed to use the webhook service.
@@ -9,14 +10,30 @@ export class WebhookClientRepository {
910 this . repository = this . dataSource . getRepository ( entities . WebhookClient ) ;
1011 }
1112
12- public async registerClient ( client : entities . WebhookClient ) : Promise < void > {
13- const existingClient = await this . repository . findOne ( {
14- where : { id : client . id } ,
15- } ) ;
16- if ( existingClient ) {
17- throw new Error ( `Client with id ${ client . id } already exists.` ) ;
13+ public async registerClient (
14+ client : Omit < entities . WebhookClient , "id" > ,
15+ ) : Promise < entities . WebhookClient > {
16+ assert (
17+ ! ( await this . hasClientByName ( client . name ) ) ,
18+ "Client with that name already exists" ,
19+ ) ;
20+ const result = await this . repository . insert ( client ) ;
21+ return result . raw [ 0 ] ;
22+ }
23+ public async upsertClient (
24+ client : Omit < entities . WebhookClient , "id" > ,
25+ ) : Promise < entities . WebhookClient > {
26+ if ( await this . hasClientByName ( client . name ) ) {
27+ return this . updateClientByName ( client ) ;
28+ } else {
29+ return this . registerClient ( client ) ;
1830 }
19- await this . repository . insert ( client ) ;
31+ }
32+ public async updateClientByName (
33+ client : Omit < entities . WebhookClient , "id" > ,
34+ ) : Promise < entities . WebhookClient > {
35+ const result = await this . repository . update ( { name : client . name } , client ) ;
36+ return result . raw [ 0 ] ;
2037 }
2138
2239 public async unregisterClient ( clientId : number ) : Promise < void > {
@@ -40,12 +57,20 @@ export class WebhookClientRepository {
4057 public async listClients ( ) : Promise < entities . WebhookClient [ ] > {
4158 return this . repository . find ( ) ;
4259 }
43-
60+ public async hasClientByName ( name : string ) : Promise < boolean > {
61+ const result = await this . repository . findOne ( { where : { name } } ) ;
62+ return exists ( result ) ;
63+ }
64+ public async getClientByName ( name : string ) : Promise < entities . WebhookClient > {
65+ const result = await this . repository . findOne ( { where : { name } } ) ;
66+ assert ( result , `Client by name: ${ name } does not exist` ) ;
67+ return result ;
68+ }
4469 public async getClientByApiKey (
4570 apiKey : string ,
4671 ) : Promise < entities . WebhookClient > {
4772 const result = await this . repository . findOne ( { where : { apiKey } } ) ;
48- assert ( result , "Invalid api key" ) ;
73+ assert ( result , `Client by apiKey: ${ apiKey } does not exist` ) ;
4974 return result ;
5075 }
5176
0 commit comments