@@ -103,10 +103,10 @@ const getUserKeyExpiry = async ({ userId, name }) => {
103
103
* @param {string } params.userId - The unique identifier for the user.
104
104
* @param {string } params.name - The name associated with the key.
105
105
* @param {string } params.value - The value to be encrypted and stored as the key's value.
106
- * @param {Date } params.expiresAt - The expiry date for the key.
106
+ * @param {Date } params.expiresAt - The expiry date for the key [optional]
107
107
* @returns {Promise<Object> } The updated or newly inserted key document.
108
108
* @description This function either updates an existing user key or inserts a new one into the database,
109
- * after encrypting the provided value. It sets the provided expiry date for the key.
109
+ * after encrypting the provided value. It sets the provided expiry date for the key (or unsets for no expiry) .
110
110
*/
111
111
const updateUserKey = async ( { userId, name, value, expiresAt = null } ) => {
112
112
const encryptedValue = await encrypt ( value ) ;
@@ -115,13 +115,15 @@ const updateUserKey = async ({ userId, name, value, expiresAt = null }) => {
115
115
name,
116
116
value : encryptedValue ,
117
117
} ;
118
-
119
- // Only add expiresAt to the update object if it's not null
118
+ const updateQuery = { $set : updateObject } ;
119
+ // add expiresAt to the update object if it's not null
120
120
if ( expiresAt ) {
121
121
updateObject . expiresAt = new Date ( expiresAt ) ;
122
+ } else {
123
+ // make sure to remove if already present
124
+ updateQuery . $unset = { expiresAt } ;
122
125
}
123
-
124
- return await Key . findOneAndUpdate ( { userId, name } , updateObject , {
126
+ return await Key . findOneAndUpdate ( { userId, name } , updateQuery , {
125
127
upsert : true ,
126
128
new : true ,
127
129
} ) . lean ( ) ;
0 commit comments