Last active
February 12, 2021 13:43
-
-
Save igorkosta/960e3e70091476fb01303113bd87e026 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { API, graphqlOperation } from 'aws-amplify'; | |
import { getUser } from '@/graphql/queries'; | |
import { createUser, updateUser } from '@/graphql/mutations'; | |
import { exclude } from '@/utils/json'; | |
const get = async (email) => { | |
try { | |
const { | |
data: { | |
getUser: user, | |
}, | |
} = await API.graphql(graphqlOperation(getUser, { email })); | |
return user; | |
} catch (error) { | |
throw new Error(error.errors); | |
} | |
}; | |
const createOrUpdate = async (input) => { | |
const { email } = input; | |
if (!email) throw new Error(`Input has to include user's primary key: 'email': ${JSON.stringify(input, null, 2)}`); | |
try { | |
const user = await get(email); | |
if (!user) { | |
await API.graphql(graphqlOperation(createUser, { input })); | |
} else { | |
// get current user data | |
// and only update the provided values | |
// createdAt, updatedAt have to be excluded | |
const update = { ...exclude(['createdAt', 'updatedAt'], user), ...input }; | |
await API.graphql(graphqlOperation(updateUser, { input: update })); | |
} | |
} catch (error) { | |
throw new Error(error.errors); | |
} | |
}; | |
export { | |
get, | |
createOrUpdate, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment