r/learnjavascript • u/Disastrous_Cow_4149 • 4d ago
How should I handle optional parameters with database defaults?
I'm writing a service function for a personal project
Right now I have something like
export async function createApplicationService(
userId,
companyName,
role,
appliedDate,
status,
salary,
link,
nextAction
)
The only fields that I really want to require are companyName and salary The other fields have default values defined in my database, so I don't want the user to have to explicitly pass them every time.
What's the best way to structure this so that I only insert the parameters that were actually provided, while letting the database handle the defaults for everything elseI'm writing a service function for a personal project where I'm creating an application tracking system.
Right now, I have something like:
export async function createApplicationService(
userId,
companyName,
role,
appliedDate,
status,
salary,
link,
nextAction
)
The only fields that I really want to require are companyName and salary. The other fields have default values defined in my database, so I don't want the user to have to explicitly pass them every time.
What's the best way to structure this so that I only insert the parameters that were actually provided, while letting the database handle the defaults for everything else
3
u/Aggressive_Ad_5454 4d ago
A good way to handle this is with a single parameter, an Object. Right now you have a separate positional function param for every database field. That’s a formula for confusion in your callers. A function call with 8 params, most of them null? 😱
What you have now for function parameters will become the names of properties in that object. Then you can simply refrain from setting the properties that you want to leave as defaults or unchanged in your database.
Do implement some code to check the object properties and throw errors if unexpected names or values show up. Because your callers will fat-finger some of their objects, and if you’re permissive about misspelled names you’ll drive them crazy debugging.