Skip to content
Init is coming / May 19 - 23
Back

transaction like functionality

  • 0
  • Cloud
Grahf
2 Apr, 2025, 20:03

As I understand it appwrite doesn't support transactions. I'm attempting to make a document in three separate collections at the same time when a user registers. If one fails I want all to fail. This is my attempt at that. Is it wrong?

TypeScript
async ({
      email,
      password,
      firstName,
      lastName,
      buildings,
      units,
      roles,
    }) => {
      const { account, databases } = createAdminClient()
      const user = await account.create(ID.unique(), email, password)

      const userDetails = await databases.createDocument(
        import.meta.env.DATABASE_ID,
        import.meta.env.USER_DETAILS_ID,
        user.$id,
        {
          firstName: firstName,
          lastName: lastName,
        },
      )

      if (!userDetails) {
        await account.deleteIdentity(user.$id)
      }

      const unitUsers = await Promise.all(
        buildings.map((building, index) => {
          databases.createDocument(
            import.meta.env.DATABASE_ID,
            import.meta.env.UNIT_USERS_ID,
            ID.unique(),
            {
              unitId: building + units[index],
              userId: user.$id,
              role: roles[index],
            },
          )
        }),
      )

      if (!unitUsers) {
        await account.deleteIdentity(user.$id)
        await databases.deleteDocument(
          import.meta.env.DATABASE_ID,
          import.meta.env.USER_DETAILS_ID,
          userDetails.$id,
        )
      }

      if (user && userDetails && unitUsers) return { registered: true }
    },
  }),
TL;DR
Kenny
2 Apr, 2025, 20:09

This looks fine but you might want to add some sort of error handling so when something goes wrong it's easy to find what happened, and you can give a useful message to the user.

Grahf
2 Apr, 2025, 20:17

OK I'm going to be testing it very soon!

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more