Skip to content

Instantly share code, notes, and snippets.

@jakes-space
Last active September 6, 2023 19:55
Show Gist options
  • Save jakes-space/a01bc373a30e72c3736b77e5c2c23a84 to your computer and use it in GitHub Desktop.
Save jakes-space/a01bc373a30e72c3736b77e5c2c23a84 to your computer and use it in GitHub Desktop.
Script to interactively update a Firestore doc
#!/bin/bash
#
# Retrieves, edits, and writes the given Firestore document.
#
# This script assumes an npm environment with the excellent json-diff package
# installed ("npm i -D json-diff"). If not, set the $DIFF environment variable
# or replace "npx json-diff" with "diff" or whatever other differ you please.
#
# The current version of this script can be found at
# https://gist.github.com/jakes-space/a01bc373a30e72c3736b77e5c2c23a84
DATABASE='(default)'
if [ -z "$EDITOR" ]; then EDITOR=vim; fi
if [ -z "$DIFF" ]; then DIFF="npx json-diff"; fi
if [ "$#" -ne 1 ]; then
echo 'Usage: patch-doc.sh <DOC_REF>' >/dev/stderr
exit 1
fi
doc_ref="$1"
if [[ "${doc_ref:0:1}" == '/' ]]; then
doc_ref="${doc_ref:1}" # Trim leading slash.
fi
project_id="$(gcloud config get-value project)"
access_token="$(gcloud auth application-default print-access-token)"
doc_url="https://firestore.googleapis.com/v1/projects/${project_id}/databases/${DATABASE}/documents/${doc_ref}"
temp_dir=$(mktemp -d)
function clean_exit {
rm -rf $temp_dir
exit $1
}
if ! curl -s --fail-with-body --request GET "${doc_url}" \
--header "Authorization: Bearer ${access_token}" \
>$temp_dir/old.json; then
echo "Can't read ${doc_url}:"
cat $temp_dir/old.json
clean_exit 2
fi
cp $temp_dir/old.json $temp_dir/new.json
"$EDITOR" $temp_dir/new.json
if cmp -s $temp_dir/old.json $temp_dir/new.json; then
echo 'No changes were made.'
clean_exit 0
fi
$DIFF $temp_dir/old.json $temp_dir/new.json
echo 'Are you sure you want to make the above changes?'
select yn in 'Yes' 'No'; do
case $yn in
Yes) break ;;
No) clean_exit 0 ;;
esac
done
if ! curl -s --fail-with-body --request PATCH "${doc_url}" \
--header "Authorization: Bearer ${access_token}" \
--header 'Content-Type: application/json' \
--data-binary @$temp_dir/new.json \
>$temp_dir/patch.json
then
echo "Can't write the new version:"
cat $temp_dir/patch.json
clean_exit 3
fi
clean_exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment