Skip to content

Commit

Permalink
feat: add audio bulk, tweaks api response (#9)
Browse files Browse the repository at this point in the history
* feat: add audio bulk, tweaks api response

* chore: remove useless
  • Loading branch information
Akiq2016 authored Jan 20, 2024
1 parent 4c28b78 commit 3e08bc5
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 33 deletions.
12 changes: 8 additions & 4 deletions apps/services/src/app/api/_rpc/r2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,12 @@ export async function putObject({
Body,
...rests
}: PutObjectParams) {
const result = await S3.send(
new PutObjectCommand({ Bucket: Bucket ?? "ovm", Key, Body, ...rests }),
);
return result;
try {
const result = await S3.send(
new PutObjectCommand({ Bucket: Bucket ?? "ovm", Key, Body, ...rests }),
);
return result;
} catch (error) {
console.log(error);
}
}
8 changes: 4 additions & 4 deletions apps/services/src/app/api/tts/ssml/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { putObject } from "../../_rpc/r2";
import { generate, SSMLOptions } from "./generate-ms-ssml";

export async function POST(request: Request) {
const { text, lang, voiceName, voiceStyle, voiceSpeed, voicePitch } =
(await request.json()) as SSMLOptions;

const { text, lang, voiceName, voiceStyle, voiceSpeed, voicePitch } = (
await request.json()
).body as SSMLOptions;
const ssml = generate({
text,
lang,
Expand Down Expand Up @@ -36,7 +36,7 @@ export async function POST(request: Request) {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.trace(error);
console.log(error);
return new Response("tts/r2 error", { status: 500 });
}
}
4 changes: 2 additions & 2 deletions apps/services/src/app/examples/text-to-speech/playground.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ export default function Playground() {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
body: JSON.stringify({ body: payload }),
})
.then((res) => res.json())
.then(({ key }) => {
const audioUrl = `${process.env.R2Host}/${key}`;
const audioUrl = `${process.env.NEXT_PUBLIC_R2Host}/${key}`;
setAudioUrl(audioUrl);
});
};
Expand Down
39 changes: 39 additions & 0 deletions apps/web/app/api/audio/bulk/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { PrismaClient, type Prisma, type Audio } from "@prisma/client";

async function createManyAudios(audios: Audio[]): Promise<void> {
const prisma = new PrismaClient();
try {
await prisma.$transaction(
audios.map((audio) =>
prisma.audio.create({
data: { ...audio },
}),
),
);
} catch (error) {
console.log(error);
}
}

export async function POST(req: Request): Promise<Response> {
const prisma = new PrismaClient();
const { audios } = (await req.json()) as {
audios: Prisma.AudioGetPayload<{ include: { material: true } }>[];
};
if (
Array.isArray(audios) &&
audios.length !== 0 &&
audios.every((audio) => audio.url && audio.detail)
) {
try {
await createManyAudios(audios).finally(() => {
void prisma.$disconnect();
});
return new Response(JSON.stringify({ status: 0, data: {} }));
} catch (error) {
return new Response(error, { status: 500 });
}
} else {
return new Response("Unexpected input types", { status: 500 });
}
}
20 changes: 8 additions & 12 deletions apps/web/app/api/audio/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { PrismaClient, type Prisma } from "@prisma/client";

const SEPARATOR = ";;";

export async function POST(req: Request): Promise<Response> {
const prisma = new PrismaClient();
const { url, detail, materialId } =
Expand All @@ -18,7 +16,13 @@ export async function POST(req: Request): Promise<Response> {
materialId,
},
});
return new Response(JSON.stringify(audio), {});
return new Response(
JSON.stringify({
status: 0,
data: { audio },
}),
{},
);
} catch (error) {
return new Response(error, { status: 500 });
}
Expand All @@ -33,21 +37,13 @@ export async function GET(req: Request): Promise<Response> {
try {
const audio = await prisma.audio.findUnique({
where: { id: id ?? undefined },
include: { material: true },
});

if (audio) {
return new Response(
JSON.stringify({
status: 0,
data: {
...audio,
material: {
...audio.material,
contentList: audio.material?.contentList.split(SEPARATOR),
imageList: audio.material?.imageList?.split(SEPARATOR),
},
},
data: { audio },
}),
{},
);
Expand Down
17 changes: 15 additions & 2 deletions apps/web/app/api/material/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ export async function POST(req: Request): Promise<Response> {
imageList: imageList.join(SEPARATOR),
},
});
return new Response(JSON.stringify(material), {});
return new Response(
JSON.stringify({
status: 0,
data: { material },
}),
{},
);
} catch (error) {
return new Response(error, { status: 500 });
}
Expand All @@ -32,8 +38,15 @@ export async function GET(req: Request): Promise<Response> {
try {
const material = await prisma.material.findUnique({
where: { id: id ?? undefined },
include: { audios: true },
});
return new Response(JSON.stringify(material || {}), {});
return new Response(
JSON.stringify({
status: 0,
data: { material },
}),
{},
);
} catch (error) {
return new Response("Validation Failed", { status: 500 });
}
Expand Down
Binary file modified apps/web/prisma/dev.db
Binary file not shown.
2 changes: 2 additions & 0 deletions apps/web/prisma/migrations/20240113090601_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Material" ADD COLUMN "audioIds" TEXT;
20 changes: 20 additions & 0 deletions apps/web/prisma/migrations/20240113092557_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Warnings:
- You are about to drop the column `audioIds` on the `Material` table. All the data in the column will be lost.
*/
-- RedefineTables
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Material" (
"id" TEXT NOT NULL PRIMARY KEY,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"contentList" TEXT NOT NULL,
"imageList" TEXT
);
INSERT INTO "new_Material" ("contentList", "createdAt", "id", "imageList", "updatedAt") SELECT "contentList", "createdAt", "id", "imageList", "updatedAt" FROM "Material";
DROP TABLE "Material";
ALTER TABLE "new_Material" RENAME TO "Material";
PRAGMA foreign_key_check;
PRAGMA foreign_keys=ON;
2 changes: 2 additions & 0 deletions apps/web/prisma/migrations/20240120081337_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- DropIndex
DROP INDEX "Audio_materialId_key";
19 changes: 10 additions & 9 deletions apps/web/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,22 @@ datasource db {
url = "file:./dev.db"
}

// material and audio is one-to-many relation.
model Material {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
contentList String // split by ;;. If has multi content, the detail field in Audio should has detail config for each content.
imageList String? // split by ;;. If exist, used for making video.
audio Audio?
contentList String // split by ;;. If has multi content, the detail field in Audio should have detail config for each content.
imageList String? // split by ;;. If exist, used for making video.
audios Audio[] // Define the one-to-many relationship
}

model Audio {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
url String // if is an empty string, means there are multi link in detail field.
detail String // should be JSON string
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
url String
detail String // Should be JSON string, e.g., { duration: 100, order: 1 }
material Material? @relation(fields: [materialId], references: [id])
materialId String? @unique
materialId String? // No @unique here, as it's a foreign key
}

0 comments on commit 3e08bc5

Please sign in to comment.