dannyeloD
Convex Community17mo ago
7 replies
dannyelo

Help using Convex Action

I'm trying to use an action because I'm calling external SDK and cryptr npm package.
But I got an error, I can't find what is wrong.

convex/facturapi.ts
'use node'

import Facturapi from 'facturapi' // external library
import { ActionCtx } from './_generated/server'
import { Id } from './_generated/dataModel'
import { internal } from './_generated/api'
const Cryptr = require('cryptr') // external library

const cryptr = new Cryptr(process.env.ENCRYPTION_SECRET || '123')

type FacturapiInstance = {
  organizationId: Id<'organizations'>
  ctx: ActionCtx
}

export const getFacturapiInstance = async ({
  organizationId,
  ctx,
}: FacturapiInstance): Promise<Facturapi> => {
  const organization = await ctx.runQuery(
    internal.internals.queries.getOrganization,
    {
      organizationId,
    },
  )
  if (!organization?.facturapiTestSecret) {
    throw new Error('Facturapi secret not found')
  }

  const decryptedKey = cryptr.decrypt(organization?.facturapiTestSecret)
  const facturapi = new Facturapi(`${decryptedKey}`)

  return facturapi
}


convex/invoices.ts
'use node'

import { action } from './_generated/server'
import { getFacturapiInstance } from './facturapi'

export const createInvoice = action({
  args: {
    organizationId: v.optional(v.id('organizations')),
  },
  handler: async (ctx, args) => {
    if (!args.organizationId) {
      throw new Error('Org ID required')
    }
    try {
      const facturapi = await getFacturapiInstance({
        organizationId: args.organizationId,
        ctx,
      })

      const invoice = {
        ... // invoice object
      }

      const createdInvoice = await facturapi.invoices.create(invoice)
      return createdInvoice
    } catch (error) {
      throw new Error(`Error creating invoice: ${error}`)
    }
  },
})


Error
invoices:createInvoice failure
Uncaught Error: Error creating invoice: Error: Unsupported state or unable to authenticate data at handler (../convex/invoices.ts:155:4)
Was this page helpful?