import fs from 'fs';
|
|
|
|
import axios, { AxiosInstance } from 'axios';
|
|
|
|
export class WaniKani {
|
|
$axios: AxiosInstance;
|
|
|
|
constructor(public apiKey = process.env['WANIKANI_API_KEY']!) {
|
|
this.$axios = axios.create({
|
|
baseURL: 'https://api.wanikani.com/v2/',
|
|
headers: {
|
|
Authorization: `Bearer ${process.env['WANIKANI_API_KEY']}`,
|
|
},
|
|
});
|
|
}
|
|
|
|
async subjects({
|
|
force,
|
|
}: {
|
|
force?: boolean;
|
|
} = {}) {
|
|
const subjects = {
|
|
data: [] as (IKanji | IRadical)[],
|
|
filename: 'wanikani.json',
|
|
load() {
|
|
this.data = JSON.parse(fs.readFileSync(this.filename, 'utf-8'));
|
|
return this.data;
|
|
},
|
|
dump(d: (IKanji | IRadical)[]) {
|
|
this.data = d;
|
|
this.finalize();
|
|
},
|
|
finalize() {
|
|
fs.writeFileSync(this.filename, JSON.stringify(this.data));
|
|
},
|
|
};
|
|
|
|
let data = subjects.load();
|
|
if (data.length && !force) {
|
|
return data;
|
|
}
|
|
data = [];
|
|
|
|
let nextURL = '/subjects?types=radical,kanji';
|
|
while (nextURL) {
|
|
const r = await this.$axios
|
|
.get<{
|
|
pages: {
|
|
next_url?: string;
|
|
};
|
|
data: (IKanji | IRadical)[];
|
|
}>(nextURL)
|
|
.then((r) => r.data);
|
|
data.push(...r.data);
|
|
console.info(r.pages.next_url);
|
|
nextURL = r.pages.next_url || '';
|
|
}
|
|
|
|
subjects.dump(data);
|
|
return data;
|
|
}
|
|
}
|
|
|
|
export interface IKanji {
|
|
id: number;
|
|
/** Actual type */
|
|
object: 'kanji';
|
|
url: string;
|
|
data_updated_at: string;
|
|
data: {
|
|
level: number;
|
|
document_url: string;
|
|
characters: string;
|
|
meanings: {
|
|
meaning: string;
|
|
primary: boolean;
|
|
}[];
|
|
readings: {
|
|
reading: string;
|
|
primary: boolean;
|
|
type: 'kunyomi' | 'onyomi';
|
|
}[];
|
|
component_subject_ids: number[];
|
|
visually_similar_subject_ids: number[];
|
|
};
|
|
}
|
|
|
|
export interface IRadical {
|
|
id: number;
|
|
/** Actual type */
|
|
object: 'radical';
|
|
url: string;
|
|
data_updated_at: string;
|
|
data: {
|
|
level: number;
|
|
document_url: string;
|
|
characters: string | null;
|
|
character_images: {
|
|
url: string;
|
|
metadata: {
|
|
inline_styles?: boolean;
|
|
dimensions?: string;
|
|
};
|
|
content_type: string;
|
|
}[];
|
|
meanings: {
|
|
meaning: string;
|
|
primary: boolean;
|
|
}[];
|
|
amalgamation_subject_ids: number[];
|
|
};
|
|
}
|