11import type { User , CreateUser } from '@logto/schemas' ;
22import { Users } from '@logto/schemas' ;
33import { PhoneNumberParser } from '@logto/shared' ;
4- import { conditionalArray , type Nullable , pick } from '@silverhand/essentials' ;
4+ import { cond , conditionalArray , type Nullable , pick } from '@silverhand/essentials' ;
55import type { CommonQueryMethods } from '@silverhand/slonik' ;
66import { sql } from '@silverhand/slonik' ;
77
@@ -12,6 +12,9 @@ import type { Search } from '#src/utils/search.js';
1212import { buildConditionsFromSearch } from '#src/utils/search.js' ;
1313import type { OmitAutoSetFields } from '#src/utils/sql.js' ;
1414import { conditionalSql , convertToIdentifiers } from '#src/utils/sql.js' ;
15+ import { validatePhoneNumber } from '#src/utils/user.js' ;
16+
17+ import { buildInsertIntoWithPool } from '../database/insert-into.js' ;
1518
1619const { table, fields } = convertToIdentifiers ( Users ) ;
1720
@@ -337,7 +340,43 @@ export const createUserQueries = (pool: CommonQueryMethods) => {
337340 id : string ,
338341 set : Partial < OmitAutoSetFields < CreateUser > > ,
339342 jsonbMode : 'replace' | 'merge' = 'merge'
340- ) => updateUser ( { set, where : { id } , jsonbMode } ) ;
343+ ) => {
344+ if ( set . primaryPhone ) {
345+ validatePhoneNumber ( set . primaryPhone ) ;
346+ }
347+
348+ return updateUser ( {
349+ set : {
350+ ...set ,
351+ ...cond (
352+ set . primaryPhone && {
353+ primaryPhone : new PhoneNumberParser ( set . primaryPhone ) . internationalNumber ,
354+ }
355+ ) ,
356+ } ,
357+ where : { id } ,
358+ jsonbMode,
359+ } ) ;
360+ } ;
361+
362+ const insertUserQuery = buildInsertIntoWithPool ( pool ) ( Users , {
363+ returning : true ,
364+ } ) ;
365+
366+ const insertUser = async ( data : OmitAutoSetFields < CreateUser > ) => {
367+ if ( data . primaryPhone ) {
368+ validatePhoneNumber ( data . primaryPhone ) ;
369+ }
370+
371+ return insertUserQuery ( {
372+ ...data ,
373+ ...cond (
374+ data . primaryPhone && {
375+ primaryPhone : new PhoneNumberParser ( data . primaryPhone ) . internationalNumber ,
376+ }
377+ ) ,
378+ } ) ;
379+ } ;
341380
342381 const deleteUserById = async ( id : string ) => {
343382 const { rowCount } = await pool . query ( sql `
@@ -395,6 +434,7 @@ export const createUserQueries = (pool: CommonQueryMethods) => {
395434 findUsers,
396435 findUsersByIds,
397436 updateUserById,
437+ insertUser,
398438 deleteUserById,
399439 deleteUserIdentity,
400440 hasActiveUsers,
0 commit comments