Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/v4-answers-sdk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@quranjs/api": minor
---

Add first-class SDK methods and types for the public Content v4 answers endpoints.
80 changes: 80 additions & 0 deletions packages/api/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,86 @@ export const handlers = [
},
),

http.get(
"https://apis.quran.foundation/content/api/v4/answers/by_ayah/:ayah_key",
({ params }) => {
return HttpResponse.json({
questions: [
{
id: "question-1",
body: "What is the context of this ayah?",
type: "CLARIFICATION",
ranges: [params.ayah_key],
surah: 2,
theme: ["Faith"],
summary: "A short summary",
references: ["Tafsir al-Tabari"],
language: "en",
status: "Published",
answers: [
{
id: "answer-1",
body: "This ayah is known as Ayat al-Kursi.",
answeredBy: "Scholar",
status: "Published",
language: "en",
},
],
},
],
totalCount: 1,
});
},
),

http.get(
"https://apis.quran.foundation/content/api/v4/answers/count_within_range",
() => {
return HttpResponse.json({
"2:255": {
total: 2,
types: {
CLARIFICATION: 1,
TAFSIR: 1,
},
},
"2:256": {
total: 1,
types: {
TAFSIR: 1,
},
},
});
},
),

http.get(
"https://apis.quran.foundation/content/api/v4/answers/:question_id",
({ params }) => {
return HttpResponse.json({
id: params.question_id,
body: "What is the context of this ayah?",
type: "CLARIFICATION",
ranges: ["2:255"],
surah: 2,
theme: ["Faith"],
summary: "A short summary",
references: ["Tafsir al-Tabari"],
language: "en",
status: "Published",
answers: [
{
id: "answer-1",
body: "This ayah is known as Ayat al-Kursi.",
answeredBy: "Scholar",
status: "Published",
language: "en",
},
],
});
},
),

http.get(
"https://apis.quran.foundation/content/api/v4/resources/verse_media",
() => {
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/lib/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const fieldsKeySet = new Set<string>([
]);
const preservedKeys = new Set([
"navigationalResultsNumber",
"pageSize",
"versesResultsNumber",
]);

Expand Down
13 changes: 13 additions & 0 deletions packages/api/src/runtime/create-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { operationCatalog } from "@/generated/contracts";
import { toUserSession } from "@/lib/http-utils";
import { createGeneratedGroups, createRawClient } from "@/lib/runtime-utils";
import { replacePathParams } from "@/lib/url";
import { QuranAnswers } from "@/sdk/answers";
import { QuranAudio } from "@/sdk/audio";
import { QuranChapters } from "@/sdk/chapters";
import { QuranFetcher } from "@/sdk/fetcher";
Expand Down Expand Up @@ -345,6 +346,7 @@ const createOAuth2Facade = (
};

const createContentFacade = (
answers: QuranAnswers,
chapters: QuranChapters,
verses: QuranVerses,
juzs: QuranJuzs,
Expand All @@ -354,6 +356,14 @@ const createContentFacade = (
raw: Record<string, RawOperation>,
) => {
return {
answers: {
byAyah: (key: VerseKey, query?: ApiParams) =>
answers.findByAyah(key, query),
countWithinRange: (from: VerseKey, to: VerseKey, query?: ApiParams) =>
answers.countWithinRange(from, to, query),
get: (questionId: string | number) =>
answers.findByQuestionId(questionId),
Comment thread
basit3407 marked this conversation as resolved.
},
audio: {
chapterRecitation: {
get: (reciterId: string, chapterId: ChapterId, query?: ApiParams) =>
Expand Down Expand Up @@ -447,6 +457,7 @@ export const createRuntimeClient = (
) => {
const fetcher = new QuranFetcher(mode, config);
fetcher.getFetch();
const answers = new QuranAnswers(fetcher);
const chapters = new QuranChapters(fetcher);
const verses = new QuranVerses(fetcher);
const juzs = new QuranJuzs(fetcher);
Expand Down Expand Up @@ -474,6 +485,7 @@ export const createRuntimeClient = (
};

const contentV4 = createContentFacade(
answers,
chapters,
verses,
juzs,
Expand Down Expand Up @@ -503,6 +515,7 @@ export const createRuntimeClient = (
});

return {
answers,
audio,
auth: {
...authV1,
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/runtime/create-public-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ export const createPublicRuntimeClient = (config: PublicClientConfig) => {
};

return {
answers: serverOnlyGuard,
Comment thread
basit3407 marked this conversation as resolved.
audio: serverOnlyGuard,
auth: {
...authV1,
Expand Down
108 changes: 108 additions & 0 deletions packages/api/src/sdk/answers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import type {
AnswerCountWithinRangeResponse,
AnswerQuestion,
AnswersByAyahResponse,
BaseApiParams,
QuranFetchClient,
VerseKey,
} from "@/types";
import { isValidVerseKey } from "@/utils";

type GetAnswersByAyahOptions = BaseApiParams & {
page?: number;
pageSize?: number;
};

type CountAnswersWithinRangeOptions = BaseApiParams;

const normalizeAnswerCountWithinRangeResponse = (
response: AnswerCountWithinRangeResponse,
): AnswerCountWithinRangeResponse => {
return Object.fromEntries(
Object.entries(response).map(([verseKey, count]) => {
if (!count.types) return [verseKey, count];

return [
verseKey,
{
...count,
types: Object.fromEntries(
Object.entries(count.types).map(([type, value]) => [
type.toUpperCase(),
value,
]),
),
},
];
}),
);
};

/**
* Quran answers API methods.
*/
export class QuranAnswers {
constructor(private fetcher: QuranFetchClient) {}

/**
* Get published answer questions linked to a specific ayah.
* @param {VerseKey} key verse key in format "chapter:verse" (e.g., "2:255")
* @param {GetAnswersByAyahOptions} options
* @example
* client.answers.findByAyah("2:255", { page: 1, pageSize: 2 })
*/
async findByAyah(
key: VerseKey,
options?: GetAnswersByAyahOptions,
): Promise<AnswersByAyahResponse> {
if (!isValidVerseKey(key)) throw new Error("Invalid verse key");

return this.fetcher.fetch<AnswersByAyahResponse>(
`/content/api/v4/answers/by_ayah/${key}`,
options,
);
}

/**
* Get a published answer question by id.
* @param {string | number} questionId question id
* @example
* client.answers.findByQuestionId("988")
*/
async findByQuestionId(
questionId: string | number,
): Promise<AnswerQuestion> {
return this.fetcher.fetch<AnswerQuestion>(
`/content/api/v4/answers/${questionId}`,
);
}

/**
* Get a verse-key to answer-count map within an inclusive ayah range.
* @param {VerseKey} from start verse key in format "chapter:verse"
* @param {VerseKey} to end verse key in format "chapter:verse"
* @param {CountAnswersWithinRangeOptions} options
* @example
* client.answers.countWithinRange("2:255", "2:256")
*/
async countWithinRange(
from: VerseKey,
to: VerseKey,
options?: CountAnswersWithinRangeOptions,
): Promise<AnswerCountWithinRangeResponse> {
if (!isValidVerseKey(from) || !isValidVerseKey(to)) {
throw new Error("Invalid verse key");
}

const response = await this.fetcher.fetch<AnswerCountWithinRangeResponse>(
"/content/api/v4/answers/count_within_range",
{
...options,
from,
to,
},
);

return normalizeAnswerCountWithinRangeResponse(response);
}
}
3 changes: 3 additions & 0 deletions packages/api/src/sdk/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { paramsToString, removeBeginningSlash } from "@/lib/url";
import { Language } from "@/types";
import humps from "humps";

import { QuranAnswers } from "./answers";
import { QuranAudio } from "./audio";
import { QuranChapters } from "./chapters";
import { QuranHadithReferences } from "./hadith-references";
Expand Down Expand Up @@ -130,6 +131,7 @@ export class QuranClient {
private fetcher: LegacyQuranFetcher;

public readonly chapters: QuranChapters;
public readonly answers: QuranAnswers;
public readonly verses: QuranVerses;
public readonly juzs: QuranJuzs;
public readonly audio: QuranAudio;
Expand All @@ -151,6 +153,7 @@ export class QuranClient {
this.fetcher = new LegacyQuranFetcher(this.config);
this.fetcher.getFetch();

this.answers = new QuranAnswers(this.fetcher);
Comment thread
basit3407 marked this conversation as resolved.
this.chapters = new QuranChapters(this.fetcher);
this.verses = new QuranVerses(this.fetcher);
this.juzs = new QuranJuzs(this.fetcher);
Expand Down
35 changes: 35 additions & 0 deletions packages/api/src/types/api/Answer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { VerseKey } from "../common/verse-key";

export interface Answer {
id: string | number;
body: string;
answeredBy?: string;
status: string;
language?: string;
}

export interface AnswerQuestion {
id: string | number;
body: string;
type: string;
ranges: VerseKey[];
surah: number;
theme?: string[];
summary?: string;
references?: string[];
language?: string;
status: string;
answers: Answer[];
}

export interface AnswersByAyahResponse {
questions: AnswerQuestion[];
totalCount?: number;
}

export interface AnswerCount {
types?: Record<string, number>;
total: number;
}

export type AnswerCountWithinRangeResponse = Record<string, AnswerCount>;
1 change: 1 addition & 0 deletions packages/api/src/types/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './ApiResponses';
export * from './Answer';
export * from './AudioData';
export * from './AudioResponse';
export * from './Chapter';
Expand Down
Loading
Loading