Skip to content

Commit

Permalink
Prisma endpoint generation added
Browse files Browse the repository at this point in the history
  • Loading branch information
rrd108 committed Mar 17, 2024
1 parent cdb504f commit 13f28af
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/templates/apiWithPrisma.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

export default defineEventHandler(async event => {
if (event.node.req.method == 'GET') {

if (event.node.req.query.id) {
const ${name} = await prisma.${name}.findUnique({ where: { id: event.node.req.query.id } })
return ${name}
}

const ${name} = await prisma.${name}.findMany()
return ${name}
}

if (event.node.req.method == 'POST') {
const data = await readBody(event)
const ${name} = await prisma.${name}.create({ data })
if (!${name}) {
throw createError({ status: 401, message: '${name} creation error' })
}
return ${name}
}

if (event.node.req.method == 'PATCH') {
const data = await readBody(event)
const ${name} = await prisma.${name}.update({ where:{ id:d ata.id }, data })
if (!${name}) {
throw createError({ status: 401, message: '${name} patch error' })
}
return ${name}
}

if (event.node.req.method == 'DELETE') {
const ${name} = await prisma.${name}.delete({ where:{ id:d ata.id }})
if (!${name}) {
throw createError({ status: 401, message: '${name} delete error' })
}
return ${name}
}
})
17 changes: 17 additions & 0 deletions src/utils/templates.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { readFileSync } from 'node:fs'
import { join } from 'pathe'

import { upperFirst } from 'scule'

interface TemplateOptions {
Expand Down Expand Up @@ -29,6 +32,19 @@ export default defineEventHandler((event) => {
`,
})

const apiWithPrisma: Template = ({ name, args }) => {
let contents = readFileSync(
join(__dirname, '../templates/apiWithPrisma.ts'),
'utf-8',
)
contents = contents.replace(/\$\{name\}/g, name)

return {
path: `server/api/${name}${applySuffix(args, httpMethods, 'method')}.ts`,
contents,
}
}

const plugin: Template = ({ name, args }) => ({
path: `plugins/${name}${applySuffix(args, ['client', 'server'], 'mode')}.ts`,
contents: `
Expand Down Expand Up @@ -109,6 +125,7 @@ const page: Template = ({ name }) => ({

export const templates = {
api,
apiWithPrisma,
plugin,
component,
composable,
Expand Down

0 comments on commit 13f28af

Please sign in to comment.