I have a web form that allows upload of data for a...
# orm-help
a
I have a web form that allows upload of data for a specific table. The form passes in a file and a database table name. How do I create records using the create method passing in the table name as a string in the call to prisma create like so prisma[table_name].create
k
what you have there should work
a
It doesn't. Typescript throws and error and it won't compile.
k
Might have to give an example
a
server.events.on('response', async function ({ info: { id: requestId } }) { const files = parseQueue[requestId]; server.log('start-parsing', { files, requestId, message: 'Start parsing', }); files && files[0] ? fs.createReadStream(files[0]) .pipe(csv()).on('data', async function(data) { console.log(data) try { const table = files[1] await prisma[table].create({ data }) } catch (err) { console.log(err) } }) .on('end', () => { console.log('Finished upload of data') }) : false });
The idea is that the user uploads csv data as a file along with a name of the table to which the data has to be added to. The table name is passed as a string. We use prisma[table] to pass in the table name as a variable.
f
Even if you typed the table name as an enumerable string, you'd still need to type the data. There's really only two ways to go around it, Option 1 - Without type safety Do
const table = files[1] as 'users' | 'posts'
and
prisma[table].create({ data: data as any })
Option 2 - With type safety
if (table === 'users') prisma.users.create({ etc })
a
Thanks. I considered Option 2. Small problem. I run a query to get tables from the database to populate the view. So even if a new table is added it will automatically get populated in the view and we can upload data to that table. Option 2 will require code changes. Would have loved an option where we can instantiate a Model using a string like so const tble = new Model(table) and then use it like before prisma[tble].create({})