Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
Created April 28, 2022 00:16
Show Gist options
  • Save farhad-taran/d1b803988a2dfe29ad9c2f6dee2a1b37 to your computer and use it in GitHub Desktop.
Save farhad-taran/d1b803988a2dfe29ad9c2f6dee2a1b37 to your computer and use it in GitHub Desktop.
DynamoDB documentClient dynamic updates

when doing updates on a document, we usually want to selectively update some fields, or remove other ones. this becomes more complex if you have multiple keys in a document or indexes as the requirements for changing the values of those fields are more strict. the following is a method which gives you the required attributes for doing a dynamic update:

private makeAttributeExpressions = (
    fields: Record<string, any>,
    documentKeys: string[],
  ) => {
    const exp = {
      UpdateExpression: '',
      ExpressionAttributeNames: {},
      ExpressionAttributeValues: {},
    };
    let setExpression = '';
    let removeExpression = '';
    Object.entries(fields).forEach(([key, item]) => {
      exp.ExpressionAttributeNames[`#${key}`] = key;
      if (documentKeys.includes(key)) {
        return;
      }
      if (item) {
        setExpression += ` #${key} = :${key},`;
        exp.ExpressionAttributeValues[`:${key}`] = item || null;
      } else {
        removeExpression += ` #${key},`;
      }
    });
    setExpression = 'SET ' + setExpression.slice(0, -1);
    removeExpression =
      removeExpression.length > 0
        ? 'REMOVE ' + removeExpression.slice(0, -1)
        : '';
    exp.UpdateExpression = setExpression + ' ' + removeExpression;
    return exp;
  };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment