repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
rylphs/TsUML
src/bin/index.ts
<reponame>rylphs/TsUML #! /usr/bin/env node import chalk from "chalk"; import * as yargs from "yargs"; import { getUrl } from "../core"; (async () => { try { if (yargs.argv.help) { console.log(chalk.yellowBright("tsuml --glob ./src/**/*.ts")); } const pattern = yargs.argv.glob; if (!pattern) { console.log(chalk.redBright("Missing --glob")); } else { const url = await getUrl("./tsconfig.json", pattern); const opn = require("opn"); opn(url); } } catch(e) { console.log(chalk.redBright(e)); } })();
rylphs/TsUML
src/demo/interfaces.ts
export interface Weapon { tryHit(fromDistance: number): boolean; } export interface Named { name: string; }
rylphs/TsUML
src/lib/index.ts
export { getUrl } from "../core";
rylphs/TsUML
src/core/index.ts
import * as fs from "fs"; import chalk from "chalk"; import { flatten, join } from "lodash"; import { findFilesByGlob, download } from "./io"; import { getAst, parseClasses, parseInterfaces, parseHeritageClauses } from "./parser"; import { emitSingleClass, emitAssociations, emitSingleInterface, emitHeritageClauses } from "./emitter"; import { SourceFile, ClassDeclaration } from "ts-simple-ast"; async function getDsl(tsConfigPath: string, pattern: string) { const sourceFilesPaths = await findFilesByGlob(pattern); console.log( chalk.yellowBright( "Matched files:\n" + sourceFilesPaths.reduce((p, c) => `${p}${c}\n`, "") ) ); const ast = getAst(tsConfigPath, sourceFilesPaths); const files = ast.getSourceFiles(); const trackedClasses = files.map((f:SourceFile) => f.getClasses()) .reduce((v:ClassDeclaration[], current: any) => { if(current.length > 0) v.push.apply(v, current); return v; }, []).map(value => value.getName()); trackedClasses.push.apply(trackedClasses, files.map((f:SourceFile) => f.getInterfaces()) .reduce((v:ClassDeclaration[], current: any) => { if(current.length > 0) v.push.apply(v, current); return v; }, []).map(value => value.getName())); console.log(trackedClasses); // parser const declarations = files.map(f => { const classes = f.getClasses(); const interfaces = f.getInterfaces(); const path = f.getFilePath(); return { fileName: path, classes: classes.map((parsedClass)=> parseClasses(parsedClass, trackedClasses)), heritageClauses: classes.map(parseHeritageClauses), interfaces: interfaces.map(parseInterfaces) }; }); // emitter const entities = declarations.map(d => { const classes = d.classes.map((c) => emitSingleClass(c.className, c.properties, c.methods)); const interfaces = d.interfaces.map((i) => emitSingleInterface(i.interfaceName, i.properties, i.methods)); const heritageClauses = d.heritageClauses.map(emitHeritageClauses); const associations = d.classes.map((c) => emitAssociations(c.className, c.properties)); //return [associations]; return [...classes, ...interfaces, ...heritageClauses, ...associations]; }); return join(flatten(entities), ","); } export async function getUrl(tsConfigPath: string, pattern: string) { const dsl = await getDsl(tsConfigPath, pattern); console.log(dsl); return await download(dsl); }
rylphs/TsUML
src/core/io.ts
<reponame>rylphs/TsUML import * as glob from "glob"; import * as request from "request"; import * as fs from "fs"; export async function findFilesByGlob(pattern: string) { return new Promise<string[]>((res, rej) => { glob(pattern, (err, files) => { if (err) { rej(err); } else { res(files); } }); }); } export async function download(dsl: string) { return new Promise<string>((resolve, reject) => { const url = "https://yuml.me/diagram/plain/class/"; const options = { form: { dsl_text: dsl } }; request.post(url, options, (err, res, body) => { if (err) { reject(err); } const svgFileName = body.replace(".png", ".svg"); const diagramUrl = `${url}${svgFileName}`; resolve(diagramUrl); }); }); };
dapoi/rs-bed-covid-indo-api
src/utils/scrape-site.ts
import cheerio from "cheerio" import axios from "axios" import { Agent } from "https" import { BASE_URL } from "~/const" const agent = new Agent({ rejectUnauthorized: false }) export const scrapeSite = async (endpoint: string) => { try { const fetchSite = await axios.get(`${BASE_URL}${endpoint}`, { httpsAgent: agent }) const html = await fetchSite.data const status = fetchSite.status const $ = cheerio.load(html) return { $, status } } catch (e) { return Promise.reject(e) } }
dapoi/rs-bed-covid-indo-api
src/const.ts
export const BASE_URL = "https://yankes.kemkes.go.id/app/siranap/"
dapoi/rs-bed-covid-indo-api
src/scrape/hospital-map.ts
<reponame>dapoi/rs-bed-covid-indo-api import axios from "axios" import { Agent } from "https" import { BASE_URL } from "~/const" import type { ResponseHospitalMap } from "~/types" const agent = new Agent({ rejectUnauthorized: false }) export const getHospitalMap = async (hospitalid: string): Promise<ResponseHospitalMap> => { const data = await axios.get(`${BASE_URL}rumah_sakit/${hospitalid}`, { httpsAgent: agent }) return Promise.resolve({ status: data.status, data: { id: hospitalid, name: data.data.data.RUMAH_SAKIT, address: data.data.data.ALAMAT, lat: data.data.data.alt, long: data.data.data.long, gmaps: `https://www.google.com/maps/search/?api=1&query=${data.data.alt},${data.data.long}`, }, }) }
dapoi/rs-bed-covid-indo-api
src/scrape/get-cities.ts
<gh_stars>0 import axios from "axios" import { Agent } from "https" import type { DataCities } from "~/types" import { BASE_URL } from "~/const" const agent = new Agent({ rejectUnauthorized: false }) export const getCities = async (provinceId: string): Promise<DataCities> => { const data = await axios.get(`${BASE_URL}Kabkota?kode_propinsi=${provinceId}`, { httpsAgent: agent }) return Promise.resolve({ cities: data.data.data.map((data: any) => ({ id: data.kode_kabkota, name: data.nama_kabkota, })), }) }
dapoi/rs-bed-covid-indo-api
vite.config.ts
<gh_stars>0 import { defineConfig } from "vite" import { resolve } from "path" import mix, { vercelAdapter } from "vite-plugin-mix" export default defineConfig({ resolve: { alias: { "~/": `${resolve(__dirname, "src")}/`, }, }, plugins: [ mix({ handler: "./handler.ts", adapter: vercelAdapter(), }), ], })
IMakeToo/bom-radar-card
src/const.ts
export const CARD_VERSION = '1.5.0';
IMakeToo/bom-radar-card
src/types.ts
import { LovelaceCardConfig } from 'custom-card-helpers'; // TODO Add your configuration elements here for type-checking export interface BomRadarCardConfig extends LovelaceCardConfig { show_radar_coverage: boolean; show_radar_location: boolean; show_range: boolean; show_marker: boolean; show_scale: boolean; show_playback: boolean; show_recenter: boolean; static_map: boolean; show_zoom: boolean; square_map: boolean; radar_location_fill_colour: undefined; radar_location_line_colour: undefined; radar_location_radius: undefined; extra_labels: undefined; frame_count: undefined; frame_delay: undefined; marker_longitude: undefined; marker_latitude: undefined; center_longitude: undefined; center_latitude: undefined; zoom_level: undefined; type: string; name?: string; map_style?: string; show_warning?: boolean; show_error?: boolean; test_gui?: boolean; show_header_toggle?: boolean; }
IMakeToo/bom-radar-card
src/editor.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { LitElement, html, TemplateResult, css, CSSResultGroup } from 'lit'; import { HomeAssistant, fireEvent, LovelaceCardEditor } from 'custom-card-helpers'; import { ScopedRegistryHost } from '@lit-labs/scoped-registry-mixin'; import { BomRadarCardConfig } from './types'; import { customElement, property, state } from 'lit/decorators'; import { formfieldDefinition } from '../elements/formfield'; import { selectDefinition } from '../elements/select'; import { switchDefinition } from '../elements/switch'; import { textfieldDefinition } from '../elements/textfield' @customElement('bom-radar-card-editor') export class BomRadarCardEditor extends ScopedRegistryHost(LitElement) implements LovelaceCardEditor { @property({ attribute: false }) public hass?: HomeAssistant; @state() private _config?: BomRadarCardConfig; @state() private _helpers?: any; private _initialized = false; static elementDefinitions = { ...textfieldDefinition, ...selectDefinition, ...switchDefinition, ...formfieldDefinition, }; public setConfig(config: BomRadarCardConfig): void { this._config = config; this.loadCardHelpers(); } protected shouldUpdate(): boolean { if (!this._initialized) { this._initialize(); } return true; } get _name(): string { return this._config?.name || ''; } get _entity(): string { return this._config?.entity || ''; } get _show_warning(): boolean { return this._config?.show_warning || false; } get _show_error(): boolean { return this._config?.show_error || false; } protected render(): TemplateResult | void { if (!this.hass || !this._helpers) { return html``; } let config; // eslint-disable-next-line prefer-const config = this._config; return html` <div class="values"> <div class="side-by-side"> <mwc-select label="Map Style (optional)" .configValue=${'map_style'} .value=${config.map_style ? config.map_style : ''} @selected=${this._valueChangedString} @closed=${(ev)=> ev.stopPropagation()} > <mwc-list-item></mwc-list-item> <mwc-list-item value="Light">Light</mwc-list-item> <mwc-list-item value="Voyager">Voyager</mwc-list-item> <mwc-list-item value="Satellite">Satellite</mwc-list-item> <mwc-list-item value="Dark">Dark</mwc-list-item> </mwc-select> <mwc-select label="Zoom Level (optional)" .configValue=${'zoom_level'} .value=${config.zoom_level ? config.zoom_level.toString() : null} @selected=${this._valueChangedNumber} @closed=${(ev)=> ev.stopPropagation()} > <mwc-list-item></mwc-list-item> <mwc-list-item value="4">4</mwc-list-item> <mwc-list-item value="5">5</mwc-list-item> <mwc-list-item value="6">6</mwc-list-item> <mwc-list-item value="7">7</mwc-list-item> <mwc-list-item value="8">8</mwc-list-item> <mwc-list-item value="9">9</mwc-list-item> <mwc-list-item value="10">10</mwc-list-item> </mwc-select> </div> <mwc-textfield label="Map Centre Latitude (optional)" .value=${config.center_latitude ? config.center_latitude : ''} .configValue=${'center_latitude'} @input=${this._valueChangedNumber} ></mwc-textfield> <mwc-textfield label="Map Centre Longitude (optional)" .value=${config.center_longitude ? config.center_longitude : ''} .configValue=${'center_longitude'} @input=${this._valueChangedNumber} ></mwc-textfield> <mwc-textfield label="Marker Latitude (optional)" .value=${config.marker_latitude ? config.marker_latitude : ''} .configValue=${'marker_latitude'} @input=${this._valueChangedNumber} ></mwc-textfield> <mwc-textfield label="Marker Longitude (optional)" .value=${config.marker_longitude ? config.marker_longitude : ''} .configValue=${'marker_longitude'} @input=${this._valueChangedNumber} ></mwc-textfield> <div class="side-by-side"> <mwc-textfield label="Frame Count (optional)" .value=${config.frame_count ? config.frame_count : ''} .configValue=${'frame_count'} @input=${this._valueChangedNumber} ></mwc-textfield> <mwc-textfield label="Frame Delay(ms) (optional)" .value=${config.frame_delay ? config.frame_delay : ''} .configValue=${'frame_delay'} @input=${this._valueChangedNumber} ></mwc-textfield> </div> <div class="side-by-side"> <mwc-formfield .label=${"Static Map"}> <mwc-switch .checked=${config.static_map === true} .configValue=${'static_map'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Show Zoom'}> <mwc-switch .checked=${config.show_zoom === true} .configValue=${'show_zoom'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Square Map'}> <mwc-switch .checked=${config.square_map === true} .configValue=${'square_map'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> </div> <div class="side-by-side"> <mwc-formfield .label=${"Show Marker"}> <mwc-switch .checked=${config.show_marker === true} .configValue=${'show_marker'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Show Playback'}> <mwc-switch .checked=${config.show_playback === true} .configValue=${'show_playback'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Show Recenter'}> <mwc-switch .checked=${config.show_recenter === true} .configValue=${'show_recenter'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> </div> <div class="side-by-side"> <mwc-formfield .label=${"Show Scale"}> <mwc-switch .checked=${config.show_scale === true} .configValue=${'show_scale'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Show Range'}> <mwc-switch .checked=${config.show_range === true} .configValue=${'show_range'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Show Extra Labels'}> <mwc-switch .checked=${config.extra_labels === true} .configValue=${'extra_labels'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> </div> <div class="side-by-side"> <mwc-formfield .label=${"Show Radar Locations"}> <mwc-switch .checked=${config.show_radar_location === true} .configValue=${'show_radar_location'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <mwc-formfield .label=${'Show Radar Coverage'}> <mwc-switch .checked=${config.show_radar_coverage === true} .configValue=${'show_radar_coverage'} @change=${this._valueChangedSwitch} ></mwc-switch> </mwc-formfield> <div></div> </div> <div class="side-by-side"> <mwc-textfield label="Radar Location Radius (optional)" .value=${config.radar_location_radius ? config.radar_location_radius : ''} .configValue=${'radar_location_radius'} @input=${this._valueChangedNumber} ></mwc-textfield> <div></div> </div> <div class="side-by-side"> <mwc-textfield label="Radar Line Colour (optional)" .value=${config.radar_location_line_colour ? config.radar_location_line_colour : ''} .configValue=${'radar_location_line_colour'} @input=${this._valueChangedString} ></mwc-textfield> <mwc-textfield label="Radar Fill Colour (optional)" .value=${config.radar_location_fill_colour ? config.radar_location_fill_colour : ''} .configValue=${'radar_location_fill_colour'} @input=${this._valueChangedString} ></mwc-textfield> </div> </div> `; } private _initialize(): void { if (this.hass === undefined) return; if (this._config === undefined) return; if (this._helpers === undefined) return; this._initialized = true; } private async loadCardHelpers(): Promise<void> { this._helpers = await (window as any).loadCardHelpers(); } private _valueChangedSwitch(ev): void { const target = ev.target; if (!this._config || !this.hass || !target) { return; } this._config = { ...this._config, [target.configValue]: target.checked, }; fireEvent(this, 'config-changed', { config: this._config }); } private _valueChangedNumber(ev): void { if (!this._config || !this.hass) { return; } const target = ev.target; if (this[`_${target.configValue}`] === target.value) { return; } if (target.configValue) { if (target.value === '' || target.value === null) { delete this._config[target.configValue]; } else { this._config = { ...this._config, [target.configValue]: Number(target.value), }; } } fireEvent(this, 'config-changed', { config: this._config }); } private _valueChangedString(ev): void { if (!this._config || !this.hass) { return; } const target = ev.target; if (this[`_${target.configValue}`] === target.value) { return; } if (target.configValue) { if (target.value === '') { delete this._config[target.configValue]; } else { this._config = { ...this._config, [target.configValue]: target.value, }; } } fireEvent(this, 'config-changed', { config: this._config }); } static styles: CSSResultGroup = css` mwc-select, mwc-textfield { margin-bottom: 16px; display: block; } mwc-formfield { padding-bottom: 8px; } mwc-switch { --mdc-theme-secondary: var(--switch-checked-color); } .option { padding: 4px 0px; cursor: pointer; } .row { display: flex; margin-bottom: -14px; pointer-events: none; } .title { padding-left: 16px; margin-top: -6px; pointer-events: none; } .secondary { padding-left: 40px; color: var(--secondary-text-color); pointer-events: none; } .values { padding-left: 16px; background: var(--secondary-background-color); } ha-switch { padding: 16px 6px; } .side-by-side { display: flex; } .side-by-side > * { flex: 1; padding-right: 4px; } `; }
veksen/gatsby-starter-blog-forestry
src/components/Contact/styles.tsx
<filename>src/components/Contact/styles.tsx import styled from "styled-components" export const Inner = styled.span` display: flex; justify-content: center; align-items: center; position: absolute; height: 88px; top: 0; left: 0; right: 0; transition: 0.3s top; ` export const InnerHover = styled(Inner)` top: -100%; ` export const FollowOnFB = styled.a` display: flex; flex-direction: column; border-top: 2px solid #4267b2; border-bottom: 2px solid #4267b2; color: #4267b2; margin: 22px 0; height: 88px; font-size: 24px; font-weight: 700; display: flex; cursor: pointer; transition: background 0.3s ease, color 0.3s ease; overflow: hidden; position: relative; &:hover { background: #4267b2; color: #fff; } &:hover ${Inner} { top: 100%; } &:hover ${InnerHover} { top: 0; } svg { margin-right: 15px; } svg path { transition: fill 0.3s ease; fill: #4267b2; } &:hover svg path { fill: #fff; } ` // /* purgecss ignore */ // .follow-on-fb svg path { // transition: fill 0.3s ease; // fill: #4267b2; // } // /* purgecss ignore */ // .follow-on-fb:hover svg path { // fill: #fff; // } // .follow-on-fb svg { // margin-right: 15px; // }
veksen/gatsby-starter-blog-forestry
src/components/About/index.tsx
<reponame>veksen/gatsby-starter-blog-forestry import { graphql, StaticQuery, useStaticQuery } from "gatsby" import React from "react" import { HTMLContent } from "../HTMLContent" const ABOUT_QUERY = graphql` query { markdownRemark(fields: { slug: { eq: "/la-ferme/" } }) { html } } ` const About = (): JSX.Element => { const { markdownRemark } = useStaticQuery(ABOUT_QUERY) const { html } = markdownRemark return <HTMLContent className="content" content={html} /> } export default About
veksen/gatsby-starter-blog-forestry
src/components/ContactForm/index.tsx
<reponame>veksen/gatsby-starter-blog-forestry<filename>src/components/ContactForm/index.tsx import { graphql, StaticQuery } from "gatsby" import { navigate } from "gatsby-link" import React from "react" import * as SC from "./styles" function encode(data: { "form-name": string; [key: string]: string }): string { return Object.keys(data) .map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key])) .join("&") } interface ContactFormState { isValidated: boolean "bot-field": string name: string email: string message: string } class ContactForm extends React.Component<{}, ContactFormState> { state: ContactFormState = { isValidated: false, "bot-field": "", name: "", email: "", message: "" } handleChange = (e: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>) => { this.setState({ [e.target.name as string]: e.target.value }) } handleSubmit = (e: React.FormEvent) => { e.preventDefault() const form = e.target fetch("/?no-cache=1", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: encode({ "form-name": form.getAttribute("name"), ...this.state }) }) .then(() => navigate(form.getAttribute("action"))) .catch(error => alert(error)) } render() { return ( <StaticQuery query={graphql` query { markdownRemark(fields: { slug: { eq: "/contactez-nous/" } }) { frontmatter { email phone } } } `} render={data => { const { frontmatter } = data.markdownRemark const { email, phone } = frontmatter return ( <React.Fragment> {phone ? ( <SC.ContactBlock> <div className="sub">Par téléphone</div> <a className="link" href={`tel:+1-${phone}`}> {phone} </a> </SC.ContactBlock> ) : null} {email ? ( <SC.ContactBlock> <div className="sub">Par courriel</div> <a className="link" href={`mailto:${email}`}> {email} </a> </SC.ContactBlock> ) : null} <SC.ContactBlock> <div className="sub">Ou ici, directement</div> <form name="contact" method="post" action="/contact/thanks/" data-netlify="true" data-netlify-honeypot="bot-field" onSubmit={this.handleSubmit} > <input type="hidden" name="form-name" value="contact" /> <div hidden> <label> Ne pas remplir: <input name="bot-field" onChange={this.handleChange} /> </label> </div> <div className="field"> <label className="label" htmlFor="name"> Votre nom </label> <div className="control"> <input className="input" type="text" name="name" onChange={this.handleChange} id="name" required /> </div> </div> <div className="field"> <label className="label" htmlFor="email"> <NAME> </label> <div className="control"> <input className="input" type="email" name="email" onChange={this.handleChange} id="email" required placeholder="<EMAIL>" /> </div> </div> <div className="field"> <label className="label" htmlFor="message"> Message </label> <div className="control"> <textarea className="textarea" name="message" onChange={this.handleChange} id="message" required /> </div> </div> <div className="field"> <button className="button is-link" type="submit"> Soumettre › </button> </div> </form> </SC.ContactBlock> </React.Fragment> ) }} /> ) } } export default ContactForm
veksen/gatsby-starter-blog-forestry
src/components/Header/index.tsx
<reponame>veksen/gatsby-starter-blog-forestry<filename>src/components/Header/index.tsx import React, { useState } from "react" import { useStaticQuery, graphql } from "gatsby" import classNames from "classnames" import Burger from "../../icons/burger.svg" import Close from "../../icons/close.svg" import * as SC from "./styles" const BACKGROUND_QUERY = graphql` { allImageSharp(filter: { fixed: { originalName: { eq: "background.jpg" } } }) { edges { node { id fixed { src originalName } } } } } ` const Header = (props): JSX.Element => { const backgroundQuery = useStaticQuery(BACKGROUND_QUERY) const background = backgroundQuery.allImageSharp.edges[0].node.fixed.src const isHome = props.location.pathname === `${__PATH_PREFIX__}/` const [isMenuOpen, setIsMenuOpen] = useState(false) function openMenu() { setIsMenuOpen(true) } function closeMenu() { setIsMenuOpen(false) } return ( <SC.HeaderWrapper background={background} className={classNames({ extended: isHome, isOpen: isMenuOpen })} > <SC.StyledContainer> <SC.MobileWrapper> <SC.LogoWrapper to="/"> <SC.StyledLogo /> </SC.LogoWrapper> <SC.Collapser>{isMenuOpen ? <Close onClick={closeMenu} /> : <Burger onClick={openMenu} />}</SC.Collapser> </SC.MobileWrapper> <SC.Menu className={classNames({ isOpen: isMenuOpen })} > <SC.StyledLink to="/" activeClassName="active"> Accueil </SC.StyledLink> <SC.StyledLink to="/la-ferme" activeClassName="active"> La ferme </SC.StyledLink> <SC.StyledLink to="/photos" activeClassName="active"> Photos </SC.StyledLink> <SC.StyledLink to="/recettes" activeClassName="active"> Recettes </SC.StyledLink> </SC.Menu> </SC.StyledContainer> </SC.HeaderWrapper> ) } export default Header
veksen/gatsby-starter-blog-forestry
src/components/Container/styles.tsx
import styled from "styled-components" export const ContainerWrapper = styled.div` width: 865px; padding: 0 25px; max-width: 100%; margin: 0 auto; `
veksen/gatsby-starter-blog-forestry
src/components/HTMLContent/index.tsx
import React from "react" interface HTMLContentProps { content?: string className?: string } export const HTMLContent = ({ content, className }: HTMLContentProps): JSX.Element => ( <div className={className} dangerouslySetInnerHTML={content ? { __html: content } : undefined} /> )
veksen/gatsby-starter-blog-forestry
src/components/Bio/index.tsx
<gh_stars>0 import React from "react" // Import typefaces import "typeface-montserrat" import "typeface-merriweather" import profilePic from "../profile-pic.jpg" import { rhythm } from "../../utils/typography" const Bio = (): JSX.Element => { return ( <div style={{ display: "flex", marginBottom: rhythm(2.5) }} > <img src={profilePic} alt={`<NAME>`} style={{ marginRight: rhythm(1 / 2), marginBottom: 0, width: rhythm(2), height: rhythm(2) }} /> <p> Written by <strong><NAME></strong> who lives and works in San Francisco building useful things.{" "} <a href="https://twitter.com/kylemathews">You should follow him on Twitter</a> </p> </div> ) } export default Bio
veksen/gatsby-starter-blog-forestry
src/components/Title/styles.tsx
import styled from "styled-components" import { Link } from "gatsby" export const TitleWrapper = styled.h2` color: #ff806f !important; font-size: 32px; display: flex; flex-direction: column; margin-bottom: 50px !important; ` export const Back = styled(Link)` margin-top: 10px; color: #ff806f; font-size: 16px; opacity: 0.6; position: relative; &:hover { color: #ff806f; opacity: 1; } ` export const Arrow = styled.span` margin-right: 10px; @media screen and (min-width: 568px) { position: absolute; right: 100%; } `
veksen/gatsby-starter-blog-forestry
src/components/Title/index.tsx
import { Link } from "gatsby" import React from "react" import * as SC from "./styles" interface TitleProps { children: React.ReactNode backTo?: { link: string text: string } backToText?: string style?: React.CSSProperties } const Title = ({ children, backTo, ...restProps }: TitleProps): JSX.Element => ( <SC.TitleWrapper {...restProps}> {children} {backTo && ( <SC.Back to={backTo.link}> <SC.Arrow>⟵</SC.Arrow> {backTo.text} </SC.Back> )} </SC.TitleWrapper> ) export default Title
veksen/gatsby-starter-blog-forestry
src/pages/la-ferme.tsx
import React from "react" import { Link, graphql } from "gatsby" import get from "lodash/get" import Helmet from "react-helmet" import Bio from "../components/Bio" import Layout from "../components/Layout" import { rhythm } from "../utils/typography" import Container from "../components/Container" import Title from "../components/Title" import About from "../components/About" import ContactForm from "../components/ContactForm" import Contact from "../components/Contact" const BlogIndex = (props): JSX.Element => { const siteTitle = get(props, "data.site.siteMetadata.title") const siteDescription = get(props, "data.site.siteMetadata.description") const posts = get(props, "data.allMarkdownRemark.edges") console.log(posts) return ( <Layout location={props.location}> <Helmet htmlAttributes={{ lang: "fr" }} meta={[{ name: "description", content: siteDescription }]} title={siteTitle} /> <Container> <Title>À propos de la ferme</Title> <About /> <Title style={{ marginTop: "3em" }}>Contactez-nous</Title> <Contact /> <ContactForm /> {/* <BioBaskets padTop /> */} </Container> </Layout> ) } export default BlogIndex export const pageQuery = graphql` query { site { siteMetadata { title description } } allMarkdownRemark(sort: { fields: [frontmatter___publish_date], order: DESC }) { edges { node { excerpt fields { slug } frontmatter { publish_date(formatString: "MMMM DD, YYYY") title body } } } } } `
veksen/gatsby-starter-blog-forestry
src/components/Container/index.tsx
import React from "react" import * as SC from "./styles" interface ContainerProps { children: React.ReactNode className?: string style?: React.CSSProperties } const Container: React.SFC<ContainerProps> = ({ children, className, style }) => ( <SC.ContainerWrapper style={style} className={className}> {children} </SC.ContainerWrapper> ) export default Container
veksen/gatsby-starter-blog-forestry
src/pages/404.tsx
<reponame>veksen/gatsby-starter-blog-forestry import React from 'react' import Layout from '../components/Layout' const NotFoundPage = (props): JSX.Element => { return ( <Layout location={props.location}> <h1>Not Found</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Layout> ) } export default NotFoundPage
veksen/gatsby-starter-blog-forestry
src/components/Layout/index.tsx
<gh_stars>0 import React from "react" import Header from "../Header" import { rhythm, scale } from "../../utils/typography" const Layout = (props): JSX.Element => { const { location, children } = props return ( <div> <Header location={location} /> {children} </div> ) } export default Layout
veksen/gatsby-starter-blog-forestry
src/components/Contact/index.tsx
import { graphql, StaticQuery, useStaticQuery } from "gatsby" import React from "react" import { HTMLContent } from "../HTMLContent" import FBLogo from "../../assets/facebook.svg" import * as SC from "./styles" const CONTACT_QUERY = graphql` query { markdownRemark(fields: { slug: { eq: "/contactez-nous/" } }) { html frontmatter { name address { line } } } } ` const Contact = (): JSX.Element => { const { markdownRemark } = useStaticQuery(CONTACT_QUERY) const { frontmatter, html } = markdownRemark const { name, address } = frontmatter console.log(name) console.log(address) return ( <React.Fragment> <div className="sub sub-main">{name}</div> {address.length && ( <ul> {address.map(({ line }) => ( <li>{line}</li> ))} </ul> )} <HTMLContent className="content" content={html} /> <SC.FollowOnFB href="https://www.facebook.com/Ferme-de-la-Racine-Carr%C3%A9e-1189474737876101/"> <SC.Inner> <FBLogo /> Suivez-nous sur Facebook </SC.Inner> <SC.InnerHover> <FBLogo /> Suivez-nous sur Facebook </SC.InnerHover> </SC.FollowOnFB> </React.Fragment> ) } export default Contact
veksen/gatsby-starter-blog-forestry
src/pages/photos.tsx
import React, { Fragment } from "react" import { graphql, navigate } from "gatsby" import get from "lodash/get" import Helmet from "react-helmet" import Layout from "../components/Layout" import Container from "../components/Container" import Title from "../components/Title" // import PreviewCompatibleImage from "../components/PreviewCompatibleImage" const PhotosPage = (props): JSX.Element => { console.log(props) const siteTitle = get(props, "data.site.siteMetadata.title") const siteDescription = get(props, "data.site.siteMetadata.description") const photos = get(props, "data.allMarkdownRemark.nodes") console.log(photos) return ( <Layout location={props.location}> <Helmet htmlAttributes={{ lang: "fr" }} meta={[{ name: "description", content: siteDescription }]} title={siteTitle} /> <Container> <Title>Photos</Title> <div> {photos.map(photo => { return <img src={require(photo.frontmatter.image)} /> })} </div> {/* <div> {Object.keys(imagesByYear) .sort((a, b) => Number(b) - Number(a)) .map(year => { return ( <Fragment> <h3 className="gallery__year">{year}</h3> <div className="gallery-wrapper"> {imagesByYear[year].map(({ src, index }) => ( <div className="gallery-wrapper__image" onClick={() => navigate(`/photos-slider/${index + 1}`)} > <PreviewCompatibleImage style={{ maxWidth: "100%" }} imageInfo={src} /> </div> ))} </div> </Fragment> ); })} </div> */} {/* <BioBaskets padTop /> */} </Container> </Layout> ) } export default PhotosPage export const pageQuery = graphql` query { site { siteMetadata { title description } } allMarkdownRemark(filter: { fields: { slug: { regex: "/photos/" } } }) { nodes { fields { slug } frontmatter { title image } } } } `
veksen/gatsby-starter-blog-forestry
src/components/Header/styles.tsx
<reponame>veksen/gatsby-starter-blog-forestry<filename>src/components/Header/styles.tsx import styled, { css } from "styled-components" import { Link } from "gatsby" import Logo from "../../icons/logo.svg" import Container from "../Container" export const StyledContainer = styled(Container)` display: flex; align-items: flex-start; @media screen and (max-width: 767px) { flex-direction: column; } ` export const MobileWrapper = styled.div` display: flex; height: 86px; @media screen and (max-width: 767px) { flex: 0 0 auto; width: 100%; align-items: center; } ` export const LogoWrapper = styled(Link)` display: flex; align-items: center; box-shadow: none; @media screen and (max-width: 567px) { pointer-events: none; margin-right: 20px; } ` export const StyledLogo = styled(Logo)` width: 214px; ` export const Menu = styled.div` display: flex; justify-content: center; align-items: center; height: 100px; margin-left: auto; @media screen and (max-width: 767px) { flex-direction: column; height: auto; display: none; flex: 1 0 auto; width: 100%; } &.isOpen { padding-top: 30px; display: flex; justify-content: flex-start; align-items: flex-end; } ` export const StyledLink = styled(Link)` color: #f3e9de; font-size: 17px; position: relative; box-shadow: none; @media screen and (max-width: 767px) { margin-top: 15px; font-size: 24px; } & + & { margin-left: 25px; } &::after { position: absolute; top: 0; left: 0; right: 0; bottom: 0; content: ""; display: block; transition: all 0.3s; border-bottom: 2px solid #f3e9de; @media screen and (max-width: 767px) { border-color: transparent; } } &:hover { color: #f3e9de; } &:hover::after, &.active::after { top: -6px; left: -9px; right: -9px; bottom: -6px; border: 1px solid #fff; } ` export const HeaderWrapper = styled.nav<{ background: any }>` display: flex; justify-content: center; align-items: stretch; padding: 25px 0; height: 136px; background: linear-gradient(rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 100%), url(${props => props.background}) no-repeat 50% 6% / cover; transition: all 0.3s; &.extended { min-height: 450px; max-height: 731px; height: 75vh; @media screen and (max-width: 767px) { height: 350px; } } &.extended ${StyledContainer} { justify-content: center; flex-direction: column; } &.extended ${MobileWrapper} { height: auto; margin: 0 auto; } &.extended ${LogoWrapper} { flex: 1 0 auto; @media screen and (max-width: 567px) { order: 1; } } &.extended ${StyledLogo} { width: 500px; @media screen and (max-width: 767px) { max-width: 100%; margin: 0 20px; width: 214px; } } &.extended ${Menu} { flex: 0 0 100px; margin: 0 auto; order: 1; @media screen and (max-width: 767px) { flex: 1 0 auto; } } &.extended ${StyledLink} { font-size: 24px; } &.isOpen { @media screen and (max-width: 767px) { display: flex; } } @media screen and (max-width: 767px) { &.isOpen, &.isOpen.isExtended { height: 100vh; } } ` // TODO: replicate // @media screen and (max-width: 767px) { // .header-menu-open ~ .content, // .header-menu-open ~ .footer { // display: none; // } // } export const Collapser = styled.div` display: none; margin-left: auto; cursor: pointer; opacity: 0.35; user-select: none; @media screen and (max-width: 767px) { display: block; } `
veksen/gatsby-starter-blog-forestry
src/components/ContactForm/styles.tsx
<reponame>veksen/gatsby-starter-blog-forestry import styled from "styled-components"; export const ContactBlock = styled.div` & + & { margin-top: 12px; padding-top: 12px; border-top: 1px solid #b8afa4; } label { font-weight: 400; margin-top: 10px; } `
Narazaka/rpgmakermv-character-overlay
CharacterOverlay.d.ts
<reponame>Narazaka/rpgmakermv-character-overlay /// <reference types="rpgmakermv_typescript_dts" /> /** * 立ち絵 */ declare class CharacterOverlay { readonly characterName: string; readonly partsNames: string[]; readonly horizontalAlign: CharacterOverlayHorizontalAlign; readonly verticalAlign: CharacterOverlayVerticalAlign; readonly width: number; readonly height: number; onDraw?: (characterOverlay: CharacterOverlay) => void; private _x; private _y; private _active; private _visible; private _alpha; private readonly partsState; private _container?; private drawnPartsState?; private sprites?; private anchorX; private anchorY; private childX; private childY; constructor(characterName: string, partsNames: string[], width: number, height: number, {horizontalAlign, verticalAlign, top, right, bottom, left, active, visible, alpha, partsState, onDraw}?: { horizontalAlign?: CharacterOverlayHorizontalAlign; verticalAlign?: CharacterOverlayVerticalAlign; top?: number; right?: number; bottom?: number; left?: number; active?: boolean; visible?: boolean; alpha?: number; partsState?: { [partsName: string]: number; }; onDraw?: (characterOverlay: CharacterOverlay) => void; }); x: number; y: number; active: boolean; visible: boolean; alpha: number; readonly container: PIXI.Container; moveTo({top, right, bottom, left}: { top?: number; right?: number; bottom?: number; left?: number; }): void; setParts(partsName: string, id: number): void; setParts(partsState: CharacterOverlayPartsState): void; draw(): void; protected loadPartsImageFromFile(partsName: string, id: number): HTMLImageElement; private partsSprite(partsName, id); private calcAnchors(); private drawParts(); private drawPosition(); private drawActive(); private drawVisible(); private drawAlpha(); private notifyDraw(); } /** * パーツの状態 */ interface CharacterOverlayPartsState { [partsName: string]: number; } /** 水平寄せ */ declare type CharacterOverlayHorizontalAlign = "left" | "center" | "right"; /** 垂直寄せ */ declare type CharacterOverlayVerticalAlign = "top" | "center" | "bottom"; /** * 立ち絵グループ */ declare class CharacterOverlayGroup { readonly align: "left" | "right"; readonly pack: boolean; readonly sidePadding: number; readonly betweenPadding: number; onAdd?: (characterOverlayGroup: CharacterOverlayGroup, characterOverlay: CharacterOverlay) => void; characterNames: string[]; private readonly characterOverlays; private _container?; /** * constructor * @param align 寄せ方向 * @param pack 非表示キャラ分つめるか * @param sidePadding 端のpadding * @param betweenPadding キャラ間のpadding */ constructor({align, pack, sidePadding, betweenPadding, onAdd}?: { align?: "left" | "right"; pack?: boolean; sidePadding?: number; betweenPadding?: number; onAdd?: (characterOverlayGroup: CharacterOverlayGroup, characterOverlay: CharacterOverlay) => void; }); readonly container: PIXI.Container; addCharacter(characterOverlay: CharacterOverlay): void; character(characterName: string): CharacterOverlay; setOrder(characterNames: string[]): void; setActive(characterName: string | string[]): void; activate(characterName: string | string[]): void; inactivate(characterName: string | string[]): void; activateAll(): void; inactivateAll(): void; setVisible(characterName: string | string[]): void; show(characterName: string | string[]): void; hide(characterName: string | string[]): void; showAll(): void; hideAll(): void; draw(): void; protected setPositions(): void; private setPositionsVertical(); private setChildren(); private getPriority(); } interface Scene_Base { _characterOverlayLayer: WindowLayer; createCharacterOverlayLayer(): void; addCharacterOverlay(characterOverlay: CharacterOverlay): void; } interface Game_System { characterOverlayGroup: CharacterOverlayGroup; }
Narazaka/rpgmakermv-character-overlay
CharacterOverlay.ts
<filename>CharacterOverlay.ts /// <reference types="rpgmakermv_typescript_dts" /> /*: * @plugindesc 常時立ち絵を表示します * * @author Narazaka (https://narazaka.net/) * * @param align * @desc 寄せ方向 = left | right * @default right * * @param pack * @desc キャラが非表示になったときその分を寄せるか = true | false * @default true * * @param sidePadding * @desc 端からの間隔px * @default 0 * * @param betweenPadding * @desc キャラ間の間隔px * @default 0 * * @param characterName0 * @desc 0番目のキャラ名 * * @param partsNames0 * @desc 0番目のパーツ名群(空白区切り) 例: ベース 目 口 腕 服 (キャラ名があると必須) * * @param width0 * @desc 0番目の幅 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param height0 * @desc 0番目の高さ 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param horizontalAlign0 * @desc 0番目の横寄せ方向 = left | center | right * @default right * * @param verticalAlign0 * @desc 0番目の縦寄せ方向 = top | center | bottom * @default bottom * * @param top0 * @desc 0番目の縦座標 上からのpxで指定(topとbottomどちらかのみを指定) * * @param bottom0 * @desc 0番目の縦座標 下からのpxで指定(topとbottomどちらかのみを指定) * @default 0 * * @param active0 * @desc 0番目の初期アクティブ状態 = true | false * @default true * * @param visible0 * @desc 0番目の初期表示状態 = true | false * @default true * * @param alpha0 * @desc 0番目の初期透明度 = 0~1 * @default 1 * * * @param characterName1 * @desc 1番目のキャラ名 * * @param partsNames1 * @desc 1番目のパーツ名群(空白区切り) 例: ベース 目 口 腕 服 (キャラ名があると必須) * * @param width1 * @desc 1番目の幅 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param height1 * @desc 1番目の高さ 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param horizontalAlign1 * @desc 1番目の横寄せ方向 = left | center | right * @default right * * @param verticalAlign1 * @desc 1番目の縦寄せ方向 = top | center | bottom * @default bottom * * @param top1 * @desc 1番目の縦座標 上からのpxで指定(topとbottomどちらかのみを指定) * * @param bottom1 * @desc 1番目の縦座標 下からのpxで指定(topとbottomどちらかのみを指定) * @default 1 * * @param active1 * @desc 1番目の初期アクティブ状態 = true | false * @default true * * @param visible1 * @desc 1番目の初期表示状態 = true | false * @default true * * @param alpha1 * @desc 1番目の初期透明度 = 0~1 * @default 1 * * * @param characterName2 * @desc 2番目のキャラ名 * * @param partsNames2 * @desc 2番目のパーツ名群(空白区切り) 例: ベース 目 口 腕 服 (キャラ名があると必須) * * @param width2 * @desc 2番目の幅 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param height2 * @desc 2番目の高さ 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param horizontalAlign2 * @desc 2番目の横寄せ方向 = left | center | right * @default right * * @param verticalAlign2 * @desc 2番目の縦寄せ方向 = top | center | bottom * @default bottom * * @param top2 * @desc 2番目の縦座標 上からのpxで指定(topとbottomどちらかのみを指定) * * @param bottom2 * @desc 2番目の縦座標 下からのpxで指定(topとbottomどちらかのみを指定) * @default 2 * * @param active2 * @desc 2番目の初期アクティブ状態 = true | false * @default true * * @param visible2 * @desc 2番目の初期表示状態 = true | false * @default true * * @param alpha2 * @desc 2番目の初期透明度 = 0~1 * @default 1 * * * @param characterName3 * @desc 3番目のキャラ名 * * @param partsNames3 * @desc 3番目のパーツ名群(空白区切り) 例: ベース 目 口 腕 服 (キャラ名があると必須) * * @param width3 * @desc 3番目の幅 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param height3 * @desc 3番目の高さ 画像がこれより大きい場合は単にはみ出ます (キャラ名があると必須) * * @param horizontalAlign3 * @desc 3番目の横寄せ方向 = left | center | right * @default right * * @param verticalAlign3 * @desc 3番目の縦寄せ方向 = top | center | bottom * @default bottom * * @param top3 * @desc 3番目の縦座標 上からのpxで指定(topとbottomどちらかのみを指定) * * @param bottom3 * @desc 3番目の縦座標 下からのpxで指定(topとbottomどちらかのみを指定) * @default 3 * * @param active3 * @desc 3番目の初期アクティブ状態 = true | false * @default true * * @param visible3 * @desc 3番目の初期表示状態 = true | false * @default true * * @param alpha3 * @desc 3番目の初期透明度 = 0~1 * @default 1 */ /** * 立ち絵 */ class CharacterOverlay { readonly characterName: string; readonly partsNames: string[]; readonly horizontalAlign: CharacterOverlayHorizontalAlign; readonly verticalAlign: CharacterOverlayVerticalAlign; readonly width: number; readonly height: number; onDraw?: (characterOverlay: CharacterOverlay) => void; private _x: number; private _y: number; private _active: boolean; private _visible: boolean; private _alpha: number; private readonly partsState: CharacterOverlayPartsState = {}; private _container?: PIXI.Container; private drawnPartsState?: CharacterOverlayPartsState; private sprites?: {[partsName: string]: {[id: string]: PIXI.Sprite}}; private anchorX: number; private anchorY: number; private childX: number; private childY: number; constructor( characterName: string, partsNames: string[], width: number, height: number, { horizontalAlign = "right", verticalAlign = "bottom", top, right, bottom, left, active = true, visible = true, alpha = 1.0, partsState, onDraw, }: { horizontalAlign?: CharacterOverlayHorizontalAlign, verticalAlign?: CharacterOverlayVerticalAlign, top?: number, right?: number, bottom?: number, left?: number, active?: boolean, visible?: boolean, alpha?: number, partsState?: {[partsName: string]: number}, onDraw?: (characterOverlay: CharacterOverlay) => void, } = {}, ) { // do not save caches Object.defineProperties(this, { _container: { writable: true, enumerable: false, }, drawnPartsState: { writable: true, enumerable: false, }, sprites: { writable: true, enumerable: false, }, onDraw: { writable: true, enumerable: false, }, }); this.characterName = characterName; this.partsNames = partsNames; this.width = width; this.height = height; this.horizontalAlign = horizontalAlign; this.verticalAlign = verticalAlign; this.moveTo({ top, right, bottom, left }); this.calcAnchors(); this.active = active; this.visible = visible; this.alpha = alpha; this.onDraw = onDraw; if (partsState) this.setParts(partsState); } get x() { return this._x; } set x(x) { this._x = x; if (this.container.x !== x) this.drawPosition(); this.notifyDraw(); } get y() { return this._y; } set y(y) { this._y = y; if (this.container.y !== y) this.drawPosition(); this.notifyDraw(); } get active() { return this._active; } set active(active) { this._active = active; this.drawActive(); this.notifyDraw(); } get visible() { return this._visible; } set visible(visible) { this._visible = visible; this.drawVisible(); this.notifyDraw(); } get alpha() { return this._alpha; } set alpha(alpha) { this._alpha = alpha; this.drawAlpha(); this.notifyDraw(); } get container() { if (!this._container) this._container = new PIXI.Container(); return this._container; } moveTo({ top, right, bottom, left }: { top?: number, right?: number, bottom?: number, left?: number, }) { if (left != null) { this.x = left; } else if (right != null) { this.x = Graphics.boxWidth - right - this.width; } if (top != null) { this.y = top || 0; } else if (bottom != null) { this.y = Graphics.boxHeight - bottom - this.height; } } setParts(partsName: string, id: number): void; setParts(partsState: CharacterOverlayPartsState): void; setParts(partsName: CharacterOverlayPartsState | string, id?: number) { const partsState = typeof partsName === "string" ? {[partsName]: id as number} : partsName; for (const _partsName of Object.keys(partsState)) { const _id = partsState[_partsName]; this.partsSprite(_partsName, _id); this.partsState[_partsName] = _id; } this.drawParts(); this.notifyDraw(); } // セーブ復帰用 draw() { this.drawPosition(); this.drawActive(); this.drawVisible(); this.drawAlpha(); this.drawParts(); this.notifyDraw(); } protected loadPartsImageFromFile(partsName: string, id: number) { const bitmap = ImageManager.loadBitmap("img/character_overlays/", `${this.characterName}_${partsName}_${id}`); return bitmap._image; } private partsSprite(partsName: string, id: number) { if (!this.sprites) this.sprites = {}; if (!this.sprites[partsName]) this.sprites[partsName] = {}; if (!this.sprites[partsName][id]) { const image = this.loadPartsImageFromFile(partsName, id); const sprite = new PIXI.Sprite(PIXI.Texture.from(image)); sprite.anchor.x = this.anchorX; sprite.anchor.y = this.anchorY; sprite.x = this.childX; sprite.y = this.childY; this.sprites[partsName][id] = sprite; } return this.sprites[partsName][id]; } private calcAnchors() { switch (this.horizontalAlign) { case "left": this.anchorX = 0; this.childX = 0; break; case "right": this.anchorX = 1; this.childX = this.width; break; default: this.anchorX = 0.5; this.childX = this.width / 2; break; } switch (this.verticalAlign) { case "top": this.anchorY = 0; this.childY = 0; break; case "bottom": this.anchorY = 1; this.childY = this.height; break; default: this.anchorY = 0.5; this.childY = this.height / 2; break; } } private drawParts() { const container = this.container; if (!container.children.length) { let i = this.partsNames.length; while (i--) container.addChild(new PIXI.Container()); // layers } let index = 0; if (!this.drawnPartsState) this.drawnPartsState = {}; for (const partsName of this.partsNames) { const id = this.partsState[partsName] || 0; const drawnId = this.drawnPartsState[partsName] || 0; if (id === drawnId) continue; const layer = container.getChildAt(index) as PIXI.Container; if (drawnId) layer.removeChildren(); if (id) { const sprite = this.partsSprite(partsName, id); layer.addChild(sprite); } this.drawnPartsState[partsName] = id; ++index; } } private drawPosition() { this.container.x = this.x; this.container.y = this.y; } private drawActive() { const container = this.container; if (this.active) { if (container.filters) container.filters = null; } else { if (!container.filters) { const cmf = new PIXI.filters.ColorMatrixFilter(); cmf.brightness(0.6); container.filters = [cmf]; } } } private drawVisible() { this.container.visible = this.visible; } private drawAlpha() { this.container.alpha = this.alpha; } private notifyDraw() { if (this.onDraw) this.onDraw(this); } } // コメントの後にinterfaceがあるとtscのバグでコメントが外されてしまうようなので後ろに持ってくる /** * パーツの状態 */ interface CharacterOverlayPartsState { [partsName: string]: number; } /** 水平寄せ */ type CharacterOverlayHorizontalAlign = "left" | "center" | "right"; /** 垂直寄せ */ type CharacterOverlayVerticalAlign = "top" | "center" | "bottom"; /** * 立ち絵グループ */ class CharacterOverlayGroup { readonly align: "left" | "right"; readonly pack: boolean; readonly sidePadding: number; readonly betweenPadding: number; onAdd?: (characterOverlayGroup: CharacterOverlayGroup, characterOverlay: CharacterOverlay) => void; characterNames: string[] = []; private readonly characterOverlays: {[characterName: string]: CharacterOverlay} = {}; private _container?: PIXI.Container; /** * constructor * @param align 寄せ方向 * @param pack 非表示キャラ分つめるか * @param sidePadding 端のpadding * @param betweenPadding キャラ間のpadding */ constructor({ align = "right", pack = true, sidePadding = 0, betweenPadding = 0, onAdd, }: { align?: "left" | "right", pack?: boolean, sidePadding?: number, betweenPadding?: number, onAdd?: (characterOverlayGroup: CharacterOverlayGroup, characterOverlay: CharacterOverlay) => void, } = {}) { // do not save caches Object.defineProperties(this, { _container: { writable: true, enumerable: false, }, onAdd: { writable: true, enumerable: false, }, }); this.align = align; this.pack = pack; this.sidePadding = sidePadding; this.betweenPadding = betweenPadding; this.onAdd = onAdd; } get container() { if (!this._container) this._container = new PIXI.Container(); return this._container; } addCharacter(characterOverlay: CharacterOverlay) { this.characterOverlays[characterOverlay.characterName] = characterOverlay; this.characterNames.push(characterOverlay.characterName); this.setPositions(); this.setChildren(); if (this.onAdd) this.onAdd(this, characterOverlay); } character(characterName: string) { return this.characterOverlays[characterName]; } setOrder(characterNames: string[]) { this.characterNames = characterNames; this.setPositions(); } setActive(characterName: string | string[]) { const activeCharacterNamesHash: {[characterName: string]: boolean} = {}; for (const _characterName of characterName instanceof Array ? characterName : [characterName]) { activeCharacterNamesHash[_characterName] = true; } for (const _characterName of this.characterNames) { this.characterOverlays[_characterName].active = activeCharacterNamesHash[_characterName]; } } activate(characterName: string | string[]) { for (const _characterName of characterName instanceof Array ? characterName : [characterName]) { this.characterOverlays[_characterName].active = true; } } inactivate(characterName: string | string[]) { for (const _characterName of characterName instanceof Array ? characterName : [characterName]) { this.characterOverlays[_characterName].active = false; } } activateAll() { this.activate(this.characterNames); } inactivateAll() { this.inactivate(this.characterNames); } setVisible(characterName: string | string[]) { const visibleCharacterNamesHash: {[characterName: string]: boolean} = {}; for (const _characterName of characterName instanceof Array ? characterName : [characterName]) { visibleCharacterNamesHash[_characterName] = true; } for (const _characterName of this.characterNames) { this.characterOverlays[_characterName].visible = visibleCharacterNamesHash[_characterName]; } this.setPositions(); } show(characterName: string | string[]) { for (const _characterName of characterName instanceof Array ? characterName : [characterName]) { this.characterOverlays[_characterName].visible = true; } this.setPositions(); } hide(characterName: string | string[]) { for (const _characterName of characterName instanceof Array ? characterName : [characterName]) { this.characterOverlays[_characterName].visible = false; } this.setPositions(); } showAll() { this.show(this.characterNames); } hideAll() { this.hide(this.characterNames); } // セーブ復帰用 draw() { this.setChildren(); for (const characterName of this.characterNames) { const characterOverlay = this.character(characterName); characterOverlay.draw(); } } protected setPositions() { this.setPositionsVertical(); } private setPositionsVertical() { let offset = this.sidePadding; const characterNames = this.characterNames.slice(); // copy if (this.align === "right") characterNames.reverse(); for (const characterName of this.characterNames) { const characterOverlay = this.character(characterName); if (this.pack && !characterOverlay.visible) continue; characterOverlay.moveTo({ [this.align]: offset }); offset += characterOverlay.width + this.betweenPadding; } } private setChildren() { const priority = this.getPriority(); const container = this.container; this.container.removeChildren(); for (const characterName of priority) { const characterOverlay = this.character(characterName); container.addChild(characterOverlay.container); } } // active->characterNamesの優先度で重ね順を決定 private getPriority() { const priority = []; for (const characterName of this.characterNames) { const characterOverlay = this.character(characterName); if (characterOverlay.active) priority.unshift(characterName); } for (const characterName of this.characterNames) { const characterOverlay = this.character(characterName); if (!characterOverlay.active) priority.unshift(characterName); } return priority; } } interface Scene_Base { _characterOverlayLayer: WindowLayer; createCharacterOverlayLayer(): void; addCharacterOverlay(characterOverlay: CharacterOverlay): void; } interface Game_System { characterOverlayGroup: CharacterOverlayGroup; } (function() { Scene_Base.prototype.createCharacterOverlayLayer = function(this: Scene_Base) { const width = Graphics.boxWidth; const height = Graphics.boxHeight; const x = (Graphics.width - width) / 2; const y = (Graphics.height - height) / 2; this._characterOverlayLayer = new WindowLayer(); this._characterOverlayLayer.move(x, y, width, height); this.addChild(this._characterOverlayLayer); this._characterOverlayLayer.addChild($gameSystem.characterOverlayGroup.container); $gameSystem.characterOverlayGroup.draw(); }; // 立ち絵レイヤーをウインドウレイヤーの下に作ってしまう const createWindowLayer = Scene_Base.prototype.createWindowLayer; Scene_Base.prototype.createWindowLayer = function(this: Scene_Base) { this.createCharacterOverlayLayer(); createWindowLayer.apply(this, arguments); }; const params = PluginManager.parameters("CharacterOverlay"); // 新規ゲーム const createGameObjects = DataManager.createGameObjects; DataManager.createGameObjects = function() { createGameObjects.apply(this, arguments); if (!$gameSystem.characterOverlayGroup) { const align = params.align as "left" | "right"; // tslint:disable-next-line no-eval const pack = eval(params.pack || "true"); const sidePadding = Number(params.sidePadding || 0); const betweenPadding = Number(params.betweenPadding || 0); const characterOverlayGroup = new CharacterOverlayGroup({ align, pack, sidePadding, betweenPadding, }); $gameSystem.characterOverlayGroup = characterOverlayGroup; for (let index = 0; index < 4; ++index) { const characterName = params[`characterName${index}`]; if (!characterName) continue; const partsNames = params[`partsNames${index}`].split(/ +/); const width = Number(params[`width${index}`]); const height = Number(params[`height${index}`]); const horizontalAlign = params[`horizontalAlign${index}`] as CharacterOverlayHorizontalAlign; const verticalAlign = params[`verticalAlign${index}`] as CharacterOverlayVerticalAlign; const top = params[`top${index}`] == null || !params[`top${index}`].length ? undefined : Number(params[`top${index}`]); const bottom = params[`bottom${index}`] == null || !params[`bottom${index}`].length ? undefined : Number(params[`bottom${index}`]); // tslint:disable-next-line no-eval const active = eval(params[`active${index}`] || "true"); // tslint:disable-next-line no-eval const visible = eval(params[`visible${index}`] || "true"); const alpha = params[`alpha${index}`] == null || !params[`alpha${index}`].length ? undefined : Number(params[`alpha${index}`]); const characterOverlay = new CharacterOverlay( characterName, partsNames, width, height, { horizontalAlign, verticalAlign, top, bottom, active, visible, alpha, }, ); characterOverlayGroup.addCharacter(characterOverlay); } } }; /* // ロード(不要?) const extractSaveContents = DataManager.extractSaveContents; DataManager.extractSaveContents = function() { extractSaveContents.apply(this, arguments); if (!$gameSystem.characterOverlayGroup) { $gameSystem.characterOverlayGroup = new CharacterOverlayGroup(params); } };*/ const Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { Game_Interpreter_pluginCommand.call(this, command, args); const characterOverlayGroup = $gameSystem.characterOverlayGroup; switch (command) { case "CharacterOverlay_setOrder": characterOverlayGroup.setOrder(args); break; case "CharacterOverlay_setActive": characterOverlayGroup.setActive(args); break; case "CharacterOverlay_activate": characterOverlayGroup.activate(args); break; case "CharacterOverlay_inactivate": characterOverlayGroup.inactivate(args); break; case "CharacterOverlay_activateAll": characterOverlayGroup.activateAll(); break; case "CharacterOverlay_inactivateAll": characterOverlayGroup.inactivateAll(); break; case "CharacterOverlay_setVisible": characterOverlayGroup.setVisible(args); break; case "CharacterOverlay_show": characterOverlayGroup.show(args); break; case "CharacterOverlay_hide": characterOverlayGroup.hide(args); break; case "CharacterOverlay_showAll": characterOverlayGroup.showAll(); break; case "CharacterOverlay_hideAll": characterOverlayGroup.hideAll(); break; case "CharacterOverlay_alpha": characterOverlayGroup.character(args[0]).alpha = Number(args[1]); break; case "CharacterOverlay_setParts": const partsState: CharacterOverlayPartsState = {}; if (args.length % 2 !== 1) throw new Error(`CharacterOverlay_setPartsの引数は奇数である必要があります`); for (let i = 1; i < args.length; i += 2) { partsState[args[i]] = Number(args[i + 1]); } characterOverlayGroup.character(args[0]).setParts(partsState); break; } }; })();
xSNOWM4Nx/ts-lib-module
src/services/index.ts
export * from './abstractions'; export * from './crosscutting'; export * from './serviceKeys'; export * from './serviceProvider';
xSNOWM4Nx/ts-lib-module
src/services/crosscutting/navigationService.ts
<filename>src/services/crosscutting/navigationService.ts import { IService, Service } from '../abstractions'; import { IResponse, createResponse, ResponseStateEnumeration } from './../../communication'; import { NavigationTypeEnumeration, INavigationRequest } from '../../navigation'; import { LocalizationNamespaces } from '../../i18n'; export type NavigationRequestCallbackMethod = (navigationRequest: INavigationRequest) => void; interface INavigationRequestSubscriberDictionary { [key: string]: NavigationRequestCallbackMethod }; export interface INavigationService extends IService { history: Array<INavigationRequest>; show: (key: string, type: NavigationTypeEnumeration, url?: string) => void; onNavigationRequest: (contextKey: string, callbackHandler: NavigationRequestCallbackMethod) => string; offNavigationRequest: (registerKey: string) => boolean; }; export class NavigationService extends Service implements INavigationService { // INavigationService public history: Array<INavigationRequest> = []; // Props private navigationRequestSubscriberDictionary: INavigationRequestSubscriberDictionary = {}; private navigationRequestSubscriptionCounter: number = 0; private historyOverflowLimit: number = 2000; constructor(key: string) { super(key); this.display = { keyNamespace: LocalizationNamespaces.System, key: 'services.navigationservice.display', value: 'Navigation Service' }; this.description = { keyNamespace: LocalizationNamespaces.System, key: 'services.navigationservice.description', value: 'Provides all interaction options for UI navigation.' }; }; public show = (key: string, type: NavigationTypeEnumeration, url?: string) => { var navigationRequest: INavigationRequest = { key: key, type: type, url: url, timeStamp: Date.now() }; this.processNaviagtionRequest(navigationRequest); }; public onNavigationRequest = (contextKey: string, callbackHandler: NavigationRequestCallbackMethod) => { // Setup register key this.navigationRequestSubscriptionCounter++; const registerKey = `${contextKey}_${this.navigationRequestSubscriptionCounter}` // Register callback this.navigationRequestSubscriberDictionary[registerKey] = callbackHandler; this.logger.debug(`Component with key '${registerKey}' has subscribed on 'NavigationRequest'.`); this.logger.debug(`'${Object.entries(this.navigationRequestSubscriberDictionary).length}' subscribers on 'Changes'.`); return registerKey; }; public offNavigationRequest = (registerKey: string) => { // Delete callback var existingSubscriber = Object.entries(this.navigationRequestSubscriberDictionary).find(([key, value]) => key === registerKey); if (existingSubscriber) { delete this.navigationRequestSubscriberDictionary[registerKey]; this.logger.debug(`Component with key '${registerKey}' has unsubscribed on 'Changes'.`); this.logger.debug(`'${Object.entries(this.navigationRequestSubscriberDictionary).length}' subscribers on 'Changes'.`); return true; } else { this.logger.error(`Component with key '${registerKey}' not registered on 'Changes'.`); this.logger.debug(`'${Object.entries(this.navigationRequestSubscriberDictionary).length}' subscribers on 'Changes'.`); return false; }; }; protected async onStarting(): Promise<IResponse<boolean>> { return createResponse<boolean>(true, ResponseStateEnumeration.OK, []); }; protected async onStopping(): Promise<IResponse<boolean>> { return createResponse<boolean>(true, ResponseStateEnumeration.OK, []); }; private processNaviagtionRequest = (navigationRequest: INavigationRequest) => { // Execute callbacks Object.entries(this.navigationRequestSubscriberDictionary).forEach(([key, value], index) => value(navigationRequest)); // Archive navigation request this.archiveNavigationRequest(navigationRequest); // Increase service version this.updateVersion(`Navigation requested has been added [${navigationRequest.key}, ${navigationRequest.type}]`); }; private archiveNavigationRequest = (navigationRequest: INavigationRequest) => { // Add navigation request this.history.unshift(navigationRequest); if (this.history.length > this.historyOverflowLimit) this.history.pop(); }; };
xSNOWM4Nx/ts-lib-module
src/logging/log.ts
import { LogProvider } from './LogProvider'; export enum LogLevelEnumeration { Info, UserAction, Debug, Warning, Error, } export interface ILog { message: string; context: string; prefix: string; loggerKey: string; level: LogLevelEnumeration; timeStamp: number; } export interface ILogger { key: string; prefix: string; isActive: boolean; isDebugLogActive: boolean; info: (message: string, context?: string) => void; userAction: (message: string, context?: string) => void; debug: (message: string, context?: string) => void; warning: (message: string, context?: string) => void; error: (message: string, context?: string) => void; } export class Logger implements ILogger { // ILogger public key: string; public prefix: string; public isActive: boolean; public isDebugLogActive: boolean; constructor(key: string, prefix: string) { this.key = key; this.prefix = prefix; this.isActive = true; this.isDebugLogActive = false; } public info = (message: string, context?: string) => { if (!this.isActive) return; var log: ILog = { message: message, context: context ? context : this.key, prefix: this.prefix, loggerKey: this.key, level: LogLevelEnumeration.Info, timeStamp: Date.now() } this.archiveLog(log); }; public userAction = (message: string, context?: string) => { if (!this.isActive) return; var log: ILog = { message: message, context: context ? context : this.key, prefix: this.prefix, loggerKey: this.key, level: LogLevelEnumeration.UserAction, timeStamp: Date.now() } this.archiveLog(log); }; public debug = (message: string, context?: string) => { if (!this.isActive) return; if (!this.isDebugLogActive) return; var log: ILog = { message: message, context: context ? context : this.key, prefix: this.prefix, loggerKey: this.key, level: LogLevelEnumeration.Debug, timeStamp: Date.now() } this.archiveLog(log); }; public warning = (message: string, context?: string) => { if (!this.isActive) return; var log: ILog = { message: message, context: context ? context : this.key, prefix: this.prefix, loggerKey: this.key, level: LogLevelEnumeration.Warning, timeStamp: Date.now() } this.archiveLog(log); }; public error = (message: string, context?: string) => { if (!this.isActive) return; var log: ILog = { message: message, context: context ? context : this.key, prefix: this.prefix, loggerKey: this.key, level: LogLevelEnumeration.Error, timeStamp: Date.now() } this.archiveLog(log); }; private archiveLog = (log: ILog) => { // Archive log in provider LogProvider.archiveLog(log); }; }
xSNOWM4Nx/ts-lib-module
src/services/crosscutting/restService.ts
<filename>src/services/crosscutting/restService.ts<gh_stars>0 import { IService, Service } from '../abstractions'; import { IResponse, createResponse, ResponseStateEnumeration } from '../../communication'; import { LocalizationNamespaces } from '../../i18n'; export interface IRESTService extends IService { get: <T>(url: string, init?: RequestInit) => Promise<IResponse<T>>; post: <T>(url: string, data: Object | string, init?: RequestInit) => Promise<IResponse<T>>; put: <T>(url: string, data: Object | string, init?: RequestInit) => Promise<IResponse<T>>; delete: <T>(url: string, data?: Object | number, init?: RequestInit) => Promise<IResponse<T>>; setAuthorization: (authorizationHeader: string) => void; }; export class RESTService extends Service implements IRESTService { // Props private authorizationHeader: string = ''; constructor(key: string) { super(key); this.display = { keyNamespace: LocalizationNamespaces.System, key: 'services.restservice.display', value: 'REST Service' }; this.description = { keyNamespace: LocalizationNamespaces.System, key: 'services.restservice.description', value: 'Provides all interaction options for REST communication.' }; }; public get = <T>(url: string, init?: RequestInit): Promise<IResponse<T>> => { return this.invokeAsync<T>('GET', url, undefined, init); }; public post = <T>(url: string, data: Object | string, init?: RequestInit): Promise<IResponse<T>> => { return this.invokeAsync<T>('POST', url, data, init); }; public put = <T>(url: string, data: Object | string, init?: RequestInit): Promise<IResponse<T>> => { return this.invokeAsync<T>('PUT', url, data, init); }; public delete = <T>(url: string, data?: Object | number, init?: RequestInit): Promise<IResponse<T>> => { return this.invokeAsync<T>('DELETE', url, data, init); }; public setAuthorization = (authorizationHeader: string) => { this.authorizationHeader = authorizationHeader; }; protected async onStarting(): Promise<IResponse<boolean>> { return createResponse<boolean>(true, ResponseStateEnumeration.OK, []); }; protected async onStopping(): Promise<IResponse<boolean>> { return createResponse<boolean>(true, ResponseStateEnumeration.OK, []); }; private getHeaders = (data?: Object | number | string) => { var headers = new Headers(); // We only accept json as payload headers.set('Accept', 'application/json'); // We can use diffrent authorizations. `Bearer TOKEN`, `Basic USERNAME:PASSWORD`, etc. if (this.authorizationHeader !== '') headers.set('Authorization', this.authorizationHeader); // We define the type of the content by the data type if (data) { if ((typeof data === 'object')) { headers.set('Content-Type', 'application/json'); } else { headers.set('Content-Type', 'application/x-www-form-urlencoded'); } } return headers; }; private getBody = (data?: Object | number | string) => { var body = undefined; // Body data type must match "Content-Type" header if (data) { if ((typeof data === 'object')) { body = JSON.stringify(data); } else { body = String(data); } } return body; }; private getRequestInit = (init?: RequestInit) => { var requestInit: RequestInit = { mode: "same-origin", // no-cors, cors, *same-origin cache: "default", // *default, no-cache, reload, force-cache, only-if-cached credentials: "same-origin", // include, *same-origin, omit redirect: "follow", // manual, *follow, error referrer: "client", } if (init) { if (init.mode) requestInit.mode = init.mode; if (init.credentials) requestInit.credentials = init.credentials; } return requestInit; }; private invokeAsync = async <T>(method: string, url: string, data?: Object | number | string, init?: RequestInit): Promise<IResponse<T>> => { var responseOk = false; var responseStatus = 0; var responseStatusText = ''; var requestInit = this.getRequestInit(init); var headers = this.getHeaders(data); var body = this.getBody(data); requestInit.headers = headers; requestInit.body = body; if (this.isDebugModeActive) this.logger.info(`REST request '${method}' has started on url ${url}.`); return fetch(url, requestInit) .then((response: Response) => { // Save the response state responseOk = response.ok; responseStatus = response.status; responseStatusText = response.statusText; // Check how to resolve the body var responseContentType = response.headers.get("content-type"); if (responseContentType && responseContentType.indexOf("application/json") !== -1) return response.json(); else return response.text(); }).then((responseObject) => { // Setup the response object var responseData: IResponse<T> = { state: ResponseStateEnumeration.Unknown, messageStack: [] } if (this.isDebugModeActive) this.logger.info(`REST request '${method}' has returned from url ${url}. [${responseStatus}, ${responseStatusText}]`); if (responseObject == null || responseObject == undefined) { var displayKey = "services.restservice.novalidresponse"; var displayValue = `No valid response.`; var logMessage = `${displayValue} Response object is null or undefined.`; responseData.messageStack.push({ display: { keyNamespace: LocalizationNamespaces.System, key: displayKey, value: displayValue, }, context: this.key, logText: logMessage }) this.logger.error(logMessage); } else if (typeof responseObject == 'string') { var payload: any = { data: responseObject } responseData.state = ResponseStateEnumeration.OK; responseData.payload = payload; } else if (typeof responseObject == 'object') { var assertedResponseData = responseObject as IResponse<T>; if (assertedResponseData.state && assertedResponseData.messageStack && assertedResponseData.payload) { responseData.state = assertedResponseData.state; responseData.messageStack = assertedResponseData.messageStack; responseData.payload = assertedResponseData.payload; } else { responseData.state = ResponseStateEnumeration.OK; responseData.payload = responseObject; } } else { var displayKey = "services.restservice.noresponse"; var displayValue = `No response available.`; var logMessage = `${displayValue} No idea what's going on here. Go and drink a coffee.`; responseData.messageStack.push({ display: { key: displayKey, keyNamespace: LocalizationNamespaces.System, value: displayValue, }, context: this.key, logText: logMessage }) this.logger.error(logMessage); } // Fill the response object var response: IResponse<T> = { state: responseData.state, messageStack: responseData.messageStack, payload: responseData.payload, }; return response; }); }; };
xSNOWM4Nx/ts-lib-module
src/communication/response.ts
import { ILocalizableContent } from './../i18n'; export enum ResponseStateEnumeration { Unknown, OK, Error } export interface IResponseMessage { display: ILocalizableContent; context: string; logText?: string; } export interface IResponse<T> { state: ResponseStateEnumeration; messageStack: IResponseMessage[]; payload?: T; }; export const createResponse = <T>(payload: T, state: ResponseStateEnumeration = ResponseStateEnumeration.OK, messageStack: IResponseMessage[] = []) => { var response: IResponse<T> = { state: state, messageStack: messageStack, payload: payload } return response; }
xSNOWM4Nx/ts-lib-module
src/i18n/index.ts
export * from './l10n';
xSNOWM4Nx/ts-lib-module
src/services/abstractions/service.ts
import { LogProvider, ILogger } from './../../logging'; import { ILocalizableContent, LocalizationNamespaces } from './../../i18n'; import { IResponse, ResponseStateEnumeration } from './../../communication'; import { IServiceProvider } from './../serviceProvider'; export interface IServiceKeySubscriptionDictionary { [key: string]: string }; export type ChangesCallbackMethod = (version: number, reason: string, serviceKey: string) => void; interface IChangesSubscriberDictionary { [key: string]: ChangesCallbackMethod }; export enum ServiceStateEnumeration { Unknown, Initialized, Running, Stopped, Error } export interface IService { key: string; state: ServiceStateEnumeration; display: ILocalizableContent; description: ILocalizableContent; start: () => Promise<IResponse<boolean>>; stop: () => Promise<IResponse<boolean>>; onChanges: (contextKey: string, callbackHandler: ChangesCallbackMethod) => string; offChanges: (registerKey: string) => boolean; setDebugMode: (enabled: boolean) => void; } export abstract class Service implements IService { // IService public key: string; public display: ILocalizableContent; public description: ILocalizableContent; public state: ServiceStateEnumeration; // Props private version: number = 0; private changesSubscriberDictionary: IChangesSubscriberDictionary = {}; private changesSubscriptionCounter: number = 0; protected logger: ILogger; protected serviceProvider?: IServiceProvider; protected isDebugModeActive: boolean = false; constructor(key: string) { this.key = key; this.display = { keyNamespace: LocalizationNamespaces.System, key: 'global.nodisplaydefined', value: 'Service?' }; this.description = { keyNamespace: LocalizationNamespaces.System, key: 'global.nodescriptiondefined', value: 'Description?' }; this.state = ServiceStateEnumeration.Unknown; this.logger = LogProvider.getLogger(key); }; public async start() { this.logger.info(`Starting '${this.key}'.`); // Init fields this.changesSubscriberDictionary = {}; var onStartingResponse = await this.onStarting(); if (onStartingResponse.state === ResponseStateEnumeration.OK) { this.logger.info(`'${this.key}' is running.`); this.updateState(ServiceStateEnumeration.Running); } else { this.logger.error(`'${this.key}' could not be started.`); this.updateState(ServiceStateEnumeration.Error); } return onStartingResponse; }; public async stop() { this.logger.info(`Stopping '${this.key}'.`); var onStoppingResponse = await this.onStopping(); if (onStoppingResponse.state === ResponseStateEnumeration.OK) { this.logger.info(`'${this.key}' is stopped.`); this.updateState(ServiceStateEnumeration.Stopped); } else { this.logger.error(`'${this.key}' could not be stopped.`); this.updateState(ServiceStateEnumeration.Error); } // Dispose fields this.changesSubscriberDictionary = {}; return onStoppingResponse; }; public onChanges = (contextKey: string, callbackHandler: ChangesCallbackMethod) => { // Setup register key this.changesSubscriptionCounter++; const registerKey = `${contextKey}_${this.changesSubscriptionCounter}` // Register callback this.changesSubscriberDictionary[registerKey] = callbackHandler; this.logger.debug(`Component with key '${registerKey}' has subscribed on 'Changes'.`); this.logger.debug(`'${Object.entries(this.changesSubscriberDictionary).length}' subscribers on 'Changes'.`); // Execute the callback to update the handler immediately callbackHandler(this.version, 'Subscription successfully', this.key); return registerKey; }; public offChanges = (registerKey: string) => { // Delete callback var existingSubscriber = Object.entries(this.changesSubscriberDictionary).find(([key, value]) => key === registerKey); if (existingSubscriber) { delete this.changesSubscriberDictionary[registerKey]; this.logger.debug(`Component with key '${registerKey}' has unsubscribed on 'Changes'.`); this.logger.debug(`'${Object.entries(this.changesSubscriberDictionary).length}' subscribers on 'Changes'.`); return true; } else { this.logger.error(`Component with key '${registerKey}' not registered on 'Changes'.`); this.logger.debug(`'${Object.entries(this.changesSubscriberDictionary).length}' subscribers on 'Changes'.`); return false; } }; public injectServiceProvider = (serviceProvider: IServiceProvider) => { this.serviceProvider = serviceProvider; }; public setDebugMode = (enabled: boolean) => { this.isDebugModeActive = enabled; }; protected abstract onStopping(): Promise<IResponse<boolean>>; protected abstract onStarting(): Promise<IResponse<boolean>>; protected updateState = (state: ServiceStateEnumeration) => { this.state = state; this.updateVersion(`State changed to '${ServiceStateEnumeration[this.state]}'.`); }; protected updateVersion = (reason: string) => { this.version++; this.logger.debug(`Version has been updated to '${this.version}'. ${reason}`); // Execute callbacks Object.entries(this.changesSubscriberDictionary).forEach(([key, value], index) => value(this.version, reason, this.key)); }; };
xSNOWM4Nx/ts-lib-module
src/i18n/l10n.ts
export interface IDynamicValueDictionary { [key: string]: string }; export interface ILocalizableContent { key: string; keyNamespace?: string | null; value: string; dynamicValueDictionary?: IDynamicValueDictionary; } export type LocalizeMethod = (content: ILocalizableContent) => string; export class LocalizationNamespaces { public static System: string = 'system'; public static Notifications: string = 'notifications'; public static UIComponents: string = 'uicomponents'; }
xSNOWM4Nx/ts-lib-module
src/services/serviceDictionary.ts
<filename>src/services/serviceDictionary.ts import { IService } from './abstractions'; import { ServiceKeys } from './serviceKeys'; import { NavigationService } from './crosscutting/navigationService'; import { RESTService } from './crosscutting/restService'; export interface IServiceDictionary { [key: string]: IService }; export const ServiceDictionary: IServiceDictionary = { [ServiceKeys.NavigationService]: new NavigationService(ServiceKeys.NavigationService), [ServiceKeys.RESTService]: new RESTService(ServiceKeys.RESTService), };
xSNOWM4Nx/ts-lib-module
src/selection/selectable.ts
import { ILocalizableContent } from './../i18n'; export interface ISelectableBase { display: ILocalizableContent; description?: ILocalizableContent; key: string; isVisible?: boolean; }; export interface ISelectableValue<T> extends ISelectableBase { value: T; };
xSNOWM4Nx/ts-lib-module
src/helpers/index.ts
<filename>src/helpers/index.ts export * from './imageFunctions'; export * from './mathFunctions';
xSNOWM4Nx/ts-lib-module
src/index.ts
<filename>src/index.ts export * from './communication'; export * from './helpers'; export * from './i18n'; export * from './logging'; export * from './navigation'; export * from './selection'; export * from './services';
xSNOWM4Nx/ts-lib-module
src/services/crosscutting/index.ts
<reponame>xSNOWM4Nx/ts-lib-module export * from './navigationService'; export * from './restService';
xSNOWM4Nx/ts-lib-module
src/logging/LogProvider.ts
<gh_stars>0 import { ILogger, Logger, ILog, LogLevelEnumeration } from './log'; export class LogProvider { // Props public static loggers: Array<ILogger> = []; public static archive: Array<ILog> = []; public static archiveOverflowLimit: number = 5000; public static defaultPrefix: string = 'WEB'; public static isDebugLogActive: boolean = false; public static isConsoleLoggingActive: boolean = true; private static version: number = 0; private static onChangesSubscribers: Array<(version: number, reason: string) => void> = []; public static getLogger = (key: string, prefix?: string) => { var logger = LogProvider.loggers.find(l => l.key === key); if (logger) { logger.isDebugLogActive = LogProvider.isDebugLogActive; return logger; } logger = LogProvider.createLogger(key, prefix); logger.isDebugLogActive = LogProvider.isDebugLogActive; return logger; }; public static archiveLog = (log: ILog) => { LogProvider.archive.unshift(log); if (LogProvider.archive.length > LogProvider.archiveOverflowLimit) LogProvider.archive.pop(); // Increase version LogProvider.updateVersion(`New log entry received.`); if (LogProvider.isConsoleLoggingActive) { switch (log.level) { case LogLevelEnumeration.Debug: console.debug(`${log.prefix} | ${log.loggerKey} | ${log.message}`); break; case LogLevelEnumeration.Error: console.error(`${log.prefix} | ${log.loggerKey} | ${log.message}`); break; case LogLevelEnumeration.Info: console.info(`${log.prefix} | ${log.loggerKey} | ${log.message}`); break; case LogLevelEnumeration.Warning: console.warn(`${log.prefix} | ${log.loggerKey} | ${log.message}`); break; } } }; public static setDebugLog = (isActive: boolean, key?: string) => { if (!key) { LogProvider.isDebugLogActive = isActive; LogProvider.loggers.forEach(logger => logger.isDebugLogActive = isActive); // Increase version LogProvider.updateVersion(`Debug logging changed for all loggers.`); return; } var logger = LogProvider.loggers.find(logger => logger.key === key); if (logger) logger.isDebugLogActive = isActive; // Increase version LogProvider.updateVersion(`Debug logging changed for logger '${key}'.`); }; public static setActive = (isActive: boolean, key?: string) => { if (!key) { LogProvider.loggers.forEach(logger => logger.isActive = isActive); // Increase version LogProvider.updateVersion(`Activation changed for all loggers.`); return; } var logger = LogProvider.loggers.find(logger => logger.key === key); if (logger) logger.isActive = isActive; // Increase version LogProvider.updateVersion(`Activation changed for logger '${key}'.`); }; public static clearArchive = () => { // Clear main archive LogProvider.archive = []; // Increase version LogProvider.updateVersion(`All logs cleared.`); }; public static onChanges = (callbackHandler: (version: number, reason: string) => void) => { // Check if the callback handler is already registred, otherwise it will be added var index = LogProvider.onChangesSubscribers.indexOf(callbackHandler); if (index < 0) LogProvider.onChangesSubscribers.push(callbackHandler); // Execute the callback to update the handler immediately callbackHandler(LogProvider.version, 'Successfully registred'); }; public static offChanges = (callbackHandler: (version: number, reason: string) => void) => { var index = LogProvider.onChangesSubscribers.indexOf(callbackHandler); if (index >= 0) LogProvider.onChangesSubscribers.splice(index, 1); }; public static updateVersion = (reason: string) => { LogProvider.version++; // Execute callbacks LogProvider.onChangesSubscribers.forEach(callbackHandler => callbackHandler(LogProvider.version, reason)); }; private static createLogger = (key: string, prefix?: string) => { var loggerPrefix = prefix ? prefix : LogProvider.defaultPrefix; var logger = new Logger(key, loggerPrefix); LogProvider.loggers.push(logger); return logger; }; }
xSNOWM4Nx/ts-lib-module
src/selection/index.ts
export * from './selectable';
xSNOWM4Nx/ts-lib-module
src/logging/index.ts
<reponame>xSNOWM4Nx/ts-lib-module<gh_stars>0 export * from './log'; export * from './LogProvider';
xSNOWM4Nx/ts-lib-module
src/services/serviceProvider.ts
<filename>src/services/serviceProvider.ts import { IService, Service } from './abstractions'; import { IServiceDictionary, ServiceDictionary } from './serviceDictionary'; import { LogProvider, ILogger } from './../logging'; import { IResponse, ResponseStateEnumeration } from './../communication'; export interface IServiceProvider { key: string; serviceDictionary: IServiceDictionary; addService: <T extends IService>(service: T, serviceKey: string) => void; getService: <T extends IService>(serviceKey: string) => T | undefined; startServices: () => Promise<boolean>; stopServices: () => Promise<boolean>; } export class ServiceProvider implements IServiceProvider { // IServiceProvider public key: string; public serviceDictionary: IServiceDictionary; // Props private logger: ILogger; constructor(key: string) { this.key = key; this.serviceDictionary = ServiceDictionary; // Get the logger this.logger = LogProvider.getLogger(this.key); }; public addService = <T extends IService>(service: T, serviceKey: string) => { // Check if the service already exists var dictionaryPair = Object.entries(this.serviceDictionary).find(([key, value]) => key === serviceKey); if (dictionaryPair) return; // Push the new service to the dictionary this.logger.info(`Service '${serviceKey}' added.`); this.serviceDictionary[serviceKey] = service; }; public getService = <T extends IService>(serviceKey: string): T | undefined => { var dictionaryPair = Object.entries(this.serviceDictionary).find(([key, value]) => key === serviceKey); if (dictionaryPair) return dictionaryPair[1] as T; this.logger.error(`Service '${serviceKey}' not found.`); return undefined }; public startServices = async () => { this.logger.info(`'${Object.entries(this.serviceDictionary).length}' services detected.`); this.logger.info(`Starting services.`); const serviceStartPromises: Promise<IResponse<boolean>>[] = []; Object.entries(this.serviceDictionary).forEach(([key, value]) => { var service = value as Service; service.injectServiceProvider(this); serviceStartPromises.push(value.start()) }); const serviceStartResponses = await Promise.all(serviceStartPromises); const failedServices = serviceStartResponses.filter(r => r.state === ResponseStateEnumeration.Error); if (failedServices.length > 0) this.logger.error(`Not all services could be started. '${failedServices.length}' services failed!`); else this.logger.info(`All services started and ready.`); return failedServices.length === 0; }; public stopServices = async () => { this.logger.info(`'${Object.entries(this.serviceDictionary).length}' services detected.`); this.logger.info(`Stopping services.`); const serviceStopPromises: Promise<IResponse<boolean>>[] = []; Object.entries(this.serviceDictionary).forEach(([key, value]) => serviceStopPromises.push(value.stop())); const serviceStopResponses = await Promise.all(serviceStopPromises); const failedServices = serviceStopResponses.filter(r => r.state === ResponseStateEnumeration.Error); if (failedServices.length > 0) this.logger.error(`Not all services could be stopped. '${failedServices.length}' services failed!`); else this.logger.info(`All services stopped.`); return failedServices.length === 0; }; }
xSNOWM4Nx/ts-lib-module
src/services/serviceKeys.ts
<reponame>xSNOWM4Nx/ts-lib-module export class ServiceKeys { public static NavigationService: string = 'NavigationService'; public static RESTService: string = 'RESTService'; }
xSNOWM4Nx/ts-lib-module
src/navigation/navigation.ts
<filename>src/navigation/navigation.ts import { ISelectableBase } from './../selection'; export enum NavigationTypeEnumeration { View, Dialog } export interface INavigationElementBase extends ISelectableBase { importPath: string; } export interface INavigationRequest { key: string; type: NavigationTypeEnumeration; url?: string; timeStamp: number; }
xSNOWM4Nx/ts-lib-module
src/helpers/imageFunctions.ts
export const svgToImageAsync = (svgPath: string, width: number, height: number) => { return new Promise<HTMLImageElement>(resolve => { const image = new Image(width, height); image.addEventListener('load', () => resolve(image)); image.src = svgPath; }); }
dogboydog/wanikani-cli
models/user-data.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface UserData */ export interface UserData { /** * If the user is on vacation, this will be the timestamp of when that vacation started. If the user is not on vacation, this is null. * @type {Date} * @memberof UserData */ currentVacationStartedAt: any | null; /** * The current level of the user. This ignores subscription status. * @type {number} * @memberof UserData */ level: any; /** * * @type {UserPreferences} * @memberof UserData */ preferences: any; /** * The URL to the user's public facing profile page. * @type {string} * @memberof UserData */ profileUrl: any; /** * The signup date for the user. * @type {Date} * @memberof UserData */ startedAt: any; /** * * @type {UserSubscription} * @memberof UserData */ subscription: any; /** * The user's username. * @type {string} * @memberof UserData */ username: any; }
dogboydog/wanikani-cli
models/spaced-repetition-system.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import { BaseResource } from './base-resource'; /** * * @export * @interface SpacedRepetitionSystem */ export interface SpacedRepetitionSystem extends BaseResource { /** * * @type {SpacedRepetitionSystemData} * @memberof SpacedRepetitionSystem */ data: any; }
dogboydog/wanikani-cli
models/voice-actors.ts
<reponame>dogboydog/wanikani-cli<filename>models/voice-actors.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseCollection} from './base-collection'; /** * * @export * @interface VoiceActors */ export interface VoiceActors extends BaseCollection { /** * * @type {Array&lt;VoiceActor&gt;} * @memberof VoiceActors */ data: any; }
dogboydog/wanikani-cli
models/start-assignment-request.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface StartAssignmentRequest */ export interface StartAssignmentRequest { /** * * @type {string} * @memberof StartAssignmentRequest */ startedAt?: any; }
dogboydog/wanikani-cli
models/user.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseResource} from './base-resource'; /** * * @export * @interface User */ export interface User extends BaseResource { /** * * @type {UserData} * @memberof User */ data: any; }
dogboydog/wanikani-cli
models/resets.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import { BaseCollection } from './base-collection'; /** * * @export * @interface Resets */ export interface Resets extends BaseCollection { /** * * @type {Array&lt;Reset&gt;} * @memberof Resets */ data: any; }
dogboydog/wanikani-cli
models/review-statistic.ts
<reponame>dogboydog/wanikani-cli<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseResource} from './base-resource'; /** * * @export * @interface ReviewStatistic */ export interface ReviewStatistic extends BaseResource { /** * * @type {ReviewStatisticData} * @memberof ReviewStatistic */ data: any; }
dogboydog/wanikani-cli
models/base-resource.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface BaseResource */ export interface BaseResource { /** * * @type {number} * @memberof BaseResource */ id: any; /** * * @type {ResourceObjectType} * @memberof BaseResource */ object: any; /** * * @type {string} * @memberof BaseResource */ url: any; /** * * @type {Date} * @memberof BaseResource */ dataUpdatedAt: any; }
dogboydog/wanikani-cli
src/cli/common-options.ts
import {ICommandOptionDefinition} from '@zowe/imperative'; export class CommonOptions{ public static TOKEN_OPTION: ICommandOptionDefinition = { name: "token", description: "The API token used to authenticate you to the WaniKani REST API.", type: "string", required: true } }
dogboydog/wanikani-cli
src/cli/main.ts
#!/usr/bin/env node /* * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright Contributors to the Zowe Project. * */ import { IImperativeConfig, Imperative } from "@zowe/imperative"; import { inspect } from "util"; const config: IImperativeConfig = { configurationModule: __dirname + "/imperative" }; (async () => { try { await Imperative.init(config); Imperative.api.appLogger.trace("Init was successful"); Imperative.parse(); } catch (initErr) { Imperative.console.fatal("Error initializing WaniKani CLI:\n " + inspect(initErr)); process.exit(1); } })();
dogboydog/wanikani-cli
models/assignments.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseCollection} from './base-collection'; /** * * @export * @interface Assignments */ export interface Assignments extends BaseCollection { /** * * @type {Array&lt;Assignment&gt;} * @memberof Assignments */ data: any; }
dogboydog/wanikani-cli
models/summary-reviews.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface SummaryReviews */ export interface SummaryReviews { /** * When the paired subject_ids are available for reviews. All timestamps are the top of an hour. * @type {Date} * @memberof SummaryReviews */ availableAt: any; /** * Collection of unique identifiers for subjects. * @type {Array&lt;number&gt;} * @memberof SummaryReviews */ subjectIds: any; }
dogboydog/wanikani-cli
models/image-png-metadata.ts
<filename>models/image-png-metadata.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface ImagePngMetadata */ export interface ImagePngMetadata { /** * Color of the asset in hexadecimal * @type {string} * @memberof ImagePngMetadata */ color: any; /** * Dimension of the asset in pixels * @type {string} * @memberof ImagePngMetadata */ dimensions: any; /** * A name descriptor * @type {string} * @memberof ImagePngMetadata */ styleName: any; }
dogboydog/wanikani-cli
src/apis/review-api.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { CreateReviewRequest } from '../../models'; import { CreateReviewResponse } from '../../models'; import { Review } from '../../models'; import { Reviews } from '../../models'; /** * ReviewApi - axios parameter creator * @export */ export const ReviewApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Creates a review for a specific assignment_id. Using the related subject_id is also a valid alternative to using assignment_id. Some criteria must be met in order for a review to be created: available_at must be not null and in the past. When a review is registered, the associated assignment and review_statistic are both updated. These are returned in the response body under resources_updated. * @summary Create a review * @param {CreateReviewRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ createReview: async (body?: CreateReviewRequest, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/reviews`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required localVarHeaderParameter['Content-Type'] = 'application/json'; const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Retrieves a specific review by its id. * @summary Get a Specific Review * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReview: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getReview.'); } const localVarPath = `/reviews/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all reviews, ordered by ascending created_at, 500 at a time. * @summary Get All Reviews * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {Array&lt;number&gt;} [assignmentIds] Only reviews where data.assignment_id matches one of the array values are returned. * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReviews: async (ids?: Array<number>, updatedAfter?: string, assignmentIds?: Array<number>, subjectIds?: Array<number>, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/reviews`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (ids) { localVarQueryParameter['ids'] = ids; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } if (assignmentIds) { localVarQueryParameter['assignment_ids'] = assignmentIds; } if (subjectIds) { localVarQueryParameter['subject_ids'] = subjectIds; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * ReviewApi - functional programming interface * @export */ export const ReviewApiFp = function(configuration?: Configuration) { return { /** * Creates a review for a specific assignment_id. Using the related subject_id is also a valid alternative to using assignment_id. Some criteria must be met in order for a review to be created: available_at must be not null and in the past. When a review is registered, the associated assignment and review_statistic are both updated. These are returned in the response body under resources_updated. * @summary Create a review * @param {CreateReviewRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async createReview(body?: CreateReviewRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CreateReviewResponse>> { const localVarAxiosArgs = await ReviewApiAxiosParamCreator(configuration).createReview(body, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Retrieves a specific review by its id. * @summary Get a Specific Review * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getReview(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Review>> { const localVarAxiosArgs = await ReviewApiAxiosParamCreator(configuration).getReview(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all reviews, ordered by ascending created_at, 500 at a time. * @summary Get All Reviews * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {Array&lt;number&gt;} [assignmentIds] Only reviews where data.assignment_id matches one of the array values are returned. * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getReviews(ids?: Array<number>, updatedAfter?: string, assignmentIds?: Array<number>, subjectIds?: Array<number>, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Reviews>> { const localVarAxiosArgs = await ReviewApiAxiosParamCreator(configuration).getReviews(ids, updatedAfter, assignmentIds, subjectIds, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * ReviewApi - factory interface * @export */ export const ReviewApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Creates a review for a specific assignment_id. Using the related subject_id is also a valid alternative to using assignment_id. Some criteria must be met in order for a review to be created: available_at must be not null and in the past. When a review is registered, the associated assignment and review_statistic are both updated. These are returned in the response body under resources_updated. * @summary Create a review * @param {CreateReviewRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ createReview(body?: CreateReviewRequest, options?: any): AxiosPromise<CreateReviewResponse> { return ReviewApiFp(configuration).createReview(body, options).then((request) => request(axios, basePath)); }, /** * Retrieves a specific review by its id. * @summary Get a Specific Review * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReview(id: number, options?: any): AxiosPromise<Review> { return ReviewApiFp(configuration).getReview(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all reviews, ordered by ascending created_at, 500 at a time. * @summary Get All Reviews * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {Array&lt;number&gt;} [assignmentIds] Only reviews where data.assignment_id matches one of the array values are returned. * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReviews(ids?: Array<number>, updatedAfter?: string, assignmentIds?: Array<number>, subjectIds?: Array<number>, options?: any): AxiosPromise<Reviews> { return ReviewApiFp(configuration).getReviews(ids, updatedAfter, assignmentIds, subjectIds, options).then((request) => request(axios, basePath)); }, }; }; /** * ReviewApi - object-oriented interface * @export * @class ReviewApi * @extends {BaseAPI} */ export class ReviewApi extends BaseAPI { /** * Creates a review for a specific assignment_id. Using the related subject_id is also a valid alternative to using assignment_id. Some criteria must be met in order for a review to be created: available_at must be not null and in the past. When a review is registered, the associated assignment and review_statistic are both updated. These are returned in the response body under resources_updated. * @summary Create a review * @param {CreateReviewRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ReviewApi */ public createReview(body?: CreateReviewRequest, options?: any) { return ReviewApiFp(this.configuration).createReview(body, options).then((request) => request(this.axios, this.basePath)); } /** * Retrieves a specific review by its id. * @summary Get a Specific Review * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ReviewApi */ public getReview(id: number, options?: any) { return ReviewApiFp(this.configuration).getReview(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all reviews, ordered by ascending created_at, 500 at a time. * @summary Get All Reviews * @param {Array&lt;number&gt;} [ids] Only reviews where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only reviews updated after this time are returned. * @param {Array&lt;number&gt;} [assignmentIds] Only reviews where data.assignment_id matches one of the array values are returned. * @param {Array&lt;number&gt;} [subjectIds] Only reviews where data.subject_id matches one of the array values are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ReviewApi */ public getReviews(ids?: Array<number>, updatedAfter?: string, assignmentIds?: Array<number>, subjectIds?: Array<number>, options?: any) { return ReviewApiFp(this.configuration).getReviews(ids, updatedAfter, assignmentIds, subjectIds, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
models/review-statistics.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseCollection} from './base-collection'; /** * * @export * @interface ReviewStatistics */ export interface ReviewStatistics extends BaseCollection { /** * * @type {Array&lt;ReviewStatistic&gt;} * @memberof ReviewStatistics */ data: any; }
dogboydog/wanikani-cli
models/summary-data.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface SummaryData */ export interface SummaryData { /** * Details about subjects available for lessons. See table below for object structure. * @type {Array&lt;SummaryLessons&gt;} * @memberof SummaryData */ lessons: any; /** * Earliest date when the reviews are available. Is null when the user has no reviews scheduled. * @type {Date} * @memberof SummaryData */ nextReviewsAt: any | null; /** * Details about subjects available for reviews now and in the next 24 hours by the hour (total of 25 objects). See table below for object structure. * @type {Array&lt;SummaryReviews&gt;} * @memberof SummaryData */ reviews: any; }
dogboydog/wanikani-cli
src/apis/study-material-api.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { StudyMaterial } from '../../models'; import { StudyMaterials } from '../../models'; /** * StudyMaterialApi - axios parameter creator * @export */ export const StudyMaterialApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific study material by its id. * @summary Get a Specific Study Material * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getStudyMaterial: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getStudyMaterial.'); } const localVarPath = `/study_materials/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all study material, ordered by ascending created_at, 500 at a time. * @summary Get All Study Materials * @param {Array&lt;number&gt;} [ids] Only spaced_repetition_systems where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only spaced_repetition_systems updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getStudyMaterials: async (ids?: Array<number>, updatedAfter?: string, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/study_materials`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (ids) { localVarQueryParameter['ids'] = ids; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * StudyMaterialApi - functional programming interface * @export */ export const StudyMaterialApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific study material by its id. * @summary Get a Specific Study Material * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getStudyMaterial(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<StudyMaterial>> { const localVarAxiosArgs = await StudyMaterialApiAxiosParamCreator(configuration).getStudyMaterial(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all study material, ordered by ascending created_at, 500 at a time. * @summary Get All Study Materials * @param {Array&lt;number&gt;} [ids] Only spaced_repetition_systems where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only spaced_repetition_systems updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getStudyMaterials(ids?: Array<number>, updatedAfter?: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<StudyMaterials>> { const localVarAxiosArgs = await StudyMaterialApiAxiosParamCreator(configuration).getStudyMaterials(ids, updatedAfter, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * StudyMaterialApi - factory interface * @export */ export const StudyMaterialApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific study material by its id. * @summary Get a Specific Study Material * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getStudyMaterial(id: number, options?: any): AxiosPromise<StudyMaterial> { return StudyMaterialApiFp(configuration).getStudyMaterial(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all study material, ordered by ascending created_at, 500 at a time. * @summary Get All Study Materials * @param {Array&lt;number&gt;} [ids] Only spaced_repetition_systems where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only spaced_repetition_systems updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getStudyMaterials(ids?: Array<number>, updatedAfter?: string, options?: any): AxiosPromise<StudyMaterials> { return StudyMaterialApiFp(configuration).getStudyMaterials(ids, updatedAfter, options).then((request) => request(axios, basePath)); }, }; }; /** * StudyMaterialApi - object-oriented interface * @export * @class StudyMaterialApi * @extends {BaseAPI} */ export class StudyMaterialApi extends BaseAPI { /** * Retrieves a specific study material by its id. * @summary Get a Specific Study Material * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StudyMaterialApi */ public getStudyMaterial(id: number, options?: any) { return StudyMaterialApiFp(this.configuration).getStudyMaterial(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all study material, ordered by ascending created_at, 500 at a time. * @summary Get All Study Materials * @param {Array&lt;number&gt;} [ids] Only spaced_repetition_systems where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only spaced_repetition_systems updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof StudyMaterialApi */ public getStudyMaterials(ids?: Array<number>, updatedAfter?: string, options?: any) { return StudyMaterialApiFp(this.configuration).getStudyMaterials(ids, updatedAfter, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
src/cli/list/reviews/list-reviews.handler.ts
/* * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright Contributors to the Zowe Project. * */ import { ReviewStatisticsApiAxiosParamCreator } from '../../../apis'; import { IHandlerParameters, ICommandHandler } from "@zowe/imperative"; import axios from 'axios'; import { WaniKaniRequest } from '../../wanikani-request'; import { Review } from '../../../../models/review'; /** * Command handler for listing reviews * @export * @class ListReviewsHandler * @implements {ICommandHandler} */ export default class ListReviewsHandler implements ICommandHandler { /** * Command handler process - invoked by the command processor to handle the "zos-jobs delete job" * @param {IHandlerParameters} params - Command handler parameters * @returns {Promise<void>} - Fulfilled when the command completes successfully OR rejected with imperative error * @memberof JobHandler */ public async process(params: IHandlerParameters): Promise<void> { var creator = ReviewStatisticsApiAxiosParamCreator(); const reviewsResponse = await (WaniKaniRequest.makeRequest(await creator.getReviewStatistics(), params.arguments)); const flattenedData: any[] = reviewsResponse.data.data.map((entry: Review) => { const flat: any = { id: entry.id }; for (const key of Object.keys(entry.data)) { flat[key] = entry.data[key]; } return flat; }); /* Example request "data": { "created_at": "2015-06-25T12:02:10.316551Z", "subject_id": 476, "subject_type": "kanji", "meaning_correct": 8, "meaning_incorrect": 0, "meaning_max_streak": 8, "meaning_current_streak": 8, "reading_correct": 8, "reading_incorrect": 0, "reading_max_streak": 8, "reading_current_streak": 8, "percentage_correct": 100, "hidden": false } */ params.response.data.setObj(flattenedData); params.response.format.output({ header: true, output: flattenedData, format: 'table', fields: ['subject_id', 'subject_type', 'percentage_correct'] }) } }
dogboydog/wanikani-cli
models/assignment-data.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface AssignmentData */ export interface AssignmentData { /** * Timestamp when the related subject will be available in the user's review queue. * @type {Date} * @memberof AssignmentData */ availableAt: any | null; /** * Timestamp when the user reaches SRS stage 9 the first time. * @type {Date} * @memberof AssignmentData */ burnedAt: any | null; /** * Timestamp when the assignment was created. * @type {Date} * @memberof AssignmentData */ createdAt: any; /** * Indicates if the associated subject has been hidden, preventing it from appearing in lessons or reviews. * @type {boolean} * @memberof AssignmentData */ hidden: any; /** * Timestamp when the user reaches SRS stage 5 for the first time. * @type {Date} * @memberof AssignmentData */ passedAt: any | null; /** * Timestamp when the subject is resurrected and placed back in the user's review queue. * @type {Date} * @memberof AssignmentData */ resurrectedAt: any | null; /** * Current SRS stage interval. The interval range is determined by the related subject's spaced repetition system. * @type {number} * @memberof AssignmentData */ srsStage: any; /** * Timestamp when the user completes the lesson for the related subject. * @type {Date} * @memberof AssignmentData */ startedAt: any | null; /** * Unique identifier of the associated subject. * @type {number} * @memberof AssignmentData */ subjectId: any; /** * * @type {SubjectType} * @memberof AssignmentData */ subjectType: any; /** * The timestamp when the related subject has its prerequisites satisfied and is made available in lessons. * @type {Date} * @memberof AssignmentData */ unlockedAt: any | null; }
dogboydog/wanikani-cli
models/review-data.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface ReviewData */ export interface ReviewData { /** * Unique identifier of the associated assignment. * @type {number} * @memberof ReviewData */ assignmentId: any; /** * Timestamp when the review was created. * @type {Date} * @memberof ReviewData */ createdAt: any; /** * The SRS stage interval calculated from the number of correct and incorrect answers, with valid values ranging from 1 to 9 * @type {number} * @memberof ReviewData */ endingSrsStage: any; /** * The number of times the user has answered the meaning incorrectly. * @type {number} * @memberof ReviewData */ incorrectMeaningAnswers: any; /** * The number of times the user has answered the reading incorrectly. * @type {number} * @memberof ReviewData */ incorrectReadingAnswers: any; /** * Unique identifier of the associated spaced_repetition_system. * @type {number} * @memberof ReviewData */ spacedRepetitionSystemId: any; /** * The starting SRS stage interval, with valid values ranging from 1 to 8 * @type {number} * @memberof ReviewData */ startingSrsStage: any; /** * Unique identifier of the associated subject. * @type {number} * @memberof ReviewData */ subjectId: any; }
dogboydog/wanikani-cli
models/voice-actor-data.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface VoiceActorData */ export interface VoiceActorData { /** * Details about the voice actor. * @type {string} * @memberof VoiceActorData */ description: any; /** * male or female * @type {string} * @memberof VoiceActorData */ gender: any; /** * The voice actor's name * @type {string} * @memberof VoiceActorData */ name: any; }
dogboydog/wanikani-cli
models/context-sentence.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface ContextSentence */ export interface ContextSentence { /** * English translation of the sentence * @type {string} * @memberof ContextSentence */ en: any; /** * Japanese context sentence * @type {string} * @memberof ContextSentence */ ja: any; }
dogboydog/wanikani-cli
models/summary-lessons.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface SummaryLessons */ export interface SummaryLessons { /** * When the paired subject_ids are available for lessons. Always beginning of the current hour when the API endpoint is accessed. * @type {Date} * @memberof SummaryLessons */ availableAt: any; /** * Collection of unique identifiers for subjects. * @type {Array&lt;number&gt;} * @memberof SummaryLessons */ subjectIds: any; }
dogboydog/wanikani-cli
models/stage-attributes.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface StageAttributes */ export interface StageAttributes { /** * The length of time added to the time of review registration, adjusted to the beginning of the hour. * @type {number} * @memberof StageAttributes */ interval: any | null; /** * Unit of time. Can be the following: milliseconds, seconds, minutes, hours, days, and weeks. * @type {string} * @memberof StageAttributes */ intervalUnit: StageAttributesIntervalUnitEnum; /** * The position of the stage within the continuous order. * @type {number} * @memberof StageAttributes */ position: any; } /** * @export * @enum {string} */ export enum StageAttributesIntervalUnitEnum { Milliseconds = 'milliseconds', Seconds = 'seconds', Minutes = 'minutes', Hours = 'hours', Days = 'days', Weeks = 'weeks' }
dogboydog/wanikani-cli
models/create-review-request.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface CreateReviewRequest */ export interface CreateReviewRequest { /** * * @type {CreateReview} * @memberof CreateReviewRequest */ review?: any; }
dogboydog/wanikani-cli
src/apis/subject-api.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { Subject } from '../../models'; import { SubjectType } from '../../models'; import { Subjects } from '../../models'; /** * SubjectApi - axios parameter creator * @export */ export const SubjectApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific subject by its id. The structure of the response depends on the subject type. See the section on subject data structure for details. * @summary Get a Specific Subject * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSubject: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getSubject.'); } const localVarPath = `/subjects/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all subjects, ordered by ascending created_at, 500 at a time. * @summary Get All Subjects * @param {Array&lt;number&gt;} [ids] Only subjects where data.id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [types] Return subjects of the specified types. * @param {Array&lt;string&gt;} [slugs] Return subjects of the specified slug. * @param {Array&lt;number&gt;} [levels] Return subjects at the specified levels. * @param {boolean} [hidden] Return subjects which are or are not hidden from the user-facing application. * @param {string} [updatedAfter] Only subjects updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSubjects: async (ids?: Array<number>, types?: Array<SubjectType>, slugs?: Array<string>, levels?: Array<number>, hidden?: boolean, updatedAfter?: string, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/subjects`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (ids) { localVarQueryParameter['ids'] = ids; } if (types) { localVarQueryParameter['types'] = types; } if (slugs) { localVarQueryParameter['slugs'] = slugs; } if (levels) { localVarQueryParameter['levels'] = levels; } if (hidden !== undefined) { localVarQueryParameter['hidden'] = hidden; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * SubjectApi - functional programming interface * @export */ export const SubjectApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific subject by its id. The structure of the response depends on the subject type. See the section on subject data structure for details. * @summary Get a Specific Subject * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getSubject(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Subject>> { const localVarAxiosArgs = await SubjectApiAxiosParamCreator(configuration).getSubject(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all subjects, ordered by ascending created_at, 500 at a time. * @summary Get All Subjects * @param {Array&lt;number&gt;} [ids] Only subjects where data.id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [types] Return subjects of the specified types. * @param {Array&lt;string&gt;} [slugs] Return subjects of the specified slug. * @param {Array&lt;number&gt;} [levels] Return subjects at the specified levels. * @param {boolean} [hidden] Return subjects which are or are not hidden from the user-facing application. * @param {string} [updatedAfter] Only subjects updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getSubjects(ids?: Array<number>, types?: Array<SubjectType>, slugs?: Array<string>, levels?: Array<number>, hidden?: boolean, updatedAfter?: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Subjects>> { const localVarAxiosArgs = await SubjectApiAxiosParamCreator(configuration).getSubjects(ids, types, slugs, levels, hidden, updatedAfter, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * SubjectApi - factory interface * @export */ export const SubjectApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific subject by its id. The structure of the response depends on the subject type. See the section on subject data structure for details. * @summary Get a Specific Subject * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSubject(id: number, options?: any): AxiosPromise<Subject> { return SubjectApiFp(configuration).getSubject(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all subjects, ordered by ascending created_at, 500 at a time. * @summary Get All Subjects * @param {Array&lt;number&gt;} [ids] Only subjects where data.id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [types] Return subjects of the specified types. * @param {Array&lt;string&gt;} [slugs] Return subjects of the specified slug. * @param {Array&lt;number&gt;} [levels] Return subjects at the specified levels. * @param {boolean} [hidden] Return subjects which are or are not hidden from the user-facing application. * @param {string} [updatedAfter] Only subjects updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getSubjects(ids?: Array<number>, types?: Array<SubjectType>, slugs?: Array<string>, levels?: Array<number>, hidden?: boolean, updatedAfter?: string, options?: any): AxiosPromise<Subjects> { return SubjectApiFp(configuration).getSubjects(ids, types, slugs, levels, hidden, updatedAfter, options).then((request) => request(axios, basePath)); }, }; }; /** * SubjectApi - object-oriented interface * @export * @class SubjectApi * @extends {BaseAPI} */ export class SubjectApi extends BaseAPI { /** * Retrieves a specific subject by its id. The structure of the response depends on the subject type. See the section on subject data structure for details. * @summary Get a Specific Subject * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SubjectApi */ public getSubject(id: number, options?: any) { return SubjectApiFp(this.configuration).getSubject(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all subjects, ordered by ascending created_at, 500 at a time. * @summary Get All Subjects * @param {Array&lt;number&gt;} [ids] Only subjects where data.id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [types] Return subjects of the specified types. * @param {Array&lt;string&gt;} [slugs] Return subjects of the specified slug. * @param {Array&lt;number&gt;} [levels] Return subjects at the specified levels. * @param {boolean} [hidden] Return subjects which are or are not hidden from the user-facing application. * @param {string} [updatedAfter] Only subjects updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof SubjectApi */ public getSubjects(ids?: Array<number>, types?: Array<SubjectType>, slugs?: Array<string>, levels?: Array<number>, hidden?: boolean, updatedAfter?: string, options?: any) { return SubjectApiFp(this.configuration).getSubjects(ids, types, slugs, levels, hidden, updatedAfter, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
models/user-subscription.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * Details about the user's subscription state. See table below for the object structure. * @export * @interface UserSubscription */ export interface UserSubscription { /** * Whether or not the user currently has a paid subscription. * @type {boolean} * @memberof UserSubscription */ active: any; /** * The maximum level of content accessible to the user for lessons, reviews, and content review. For unsubscribed/free users, the maximum level is 3. For subscribed users, this is 60. Any application that uses data from the WaniKani API must respect these access limits. * @type {number} * @memberof UserSubscription */ maxLevelGranted: any; /** * The date when the user's subscription period ends. If the user has subscription type lifetime or free then the value is null. * @type {Date} * @memberof UserSubscription */ periodEndsAt: any | null; /** * The type of subscription the user has. Options are following: free, recurring, and lifetime. * @type {string} * @memberof UserSubscription */ type: UserSubscriptionTypeEnum; } /** * @export * @enum {string} */ export enum UserSubscriptionTypeEnum { Free = 'free', Recurring = 'recurring', Lifetime = 'lifetime' }
dogboydog/wanikani-cli
models/collection-object-type.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @enum {string} */ export enum CollectionObjectType { Collection = 'collection', Report = 'report' }
dogboydog/wanikani-cli
models/common-subject.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface CommonSubject */ export interface CommonSubject { /** * Collection of auxiliary meanings. See table below for the object structure. * @type {Array&lt;AuxiliaryMeaning&gt;} * @memberof CommonSubject */ auxiliaryMeanings: any; /** * The UTF-8 characters for the subject, including kanji and hiragana. * @type {string} * @memberof CommonSubject */ characters: any; /** * Timestamp when the subject was created. * @type {Date} * @memberof CommonSubject */ createdAt: any; /** * A URL pointing to the page on wanikani.com that provides detailed information about this subject. * @type {string} * @memberof CommonSubject */ documentUrl: any; /** * Timestamp when the subject was hidden, indicating associated assignments will no longer appear in lessons or reviews and that the subject page is no longer visible on wanikani.com. * @type {Date} * @memberof CommonSubject */ hiddenAt: any | null; /** * The position that the subject appears in lessons. Note that the value is scoped to the level of the subject, so there are duplicate values across levels. * @type {number} * @memberof CommonSubject */ lessonPosition: any; /** * The level of the subject, from 1 to 60. * @type {number} * @memberof CommonSubject */ level: any; /** * The subject's meaning mnemonic. * @type {string} * @memberof CommonSubject */ meaningMnemonic: any; /** * The subject meanings. * @type {Array&lt;Meaning&gt;} * @memberof CommonSubject */ meanings: any; /** * The string that is used when generating the document URL for the subject. Radicals use their meaning, downcased. Kanji and vocabulary use their characters. * @type {string} * @memberof CommonSubject */ slug: any; /** * Unique identifier of the associated spaced_repetition_system. * @type {number} * @memberof CommonSubject */ spacedRepetitionSystemId: any; }
dogboydog/wanikani-cli
models/user-preferences.ts
<filename>models/user-preferences.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * User settings specific to the WaniKani application. See table below for the object structure. * @export * @interface UserPreferences */ export interface UserPreferences { /** * The voice actor to be used for lessons and reviews. The value is associated to subject.pronunciation_audios.metadata.voice_actor_id. * @type {number} * @memberof UserPreferences */ defaultVoiceActorId: any; /** * Automatically play pronunciation audio for vocabulary during lessons. * @type {boolean} * @memberof UserPreferences */ lessonsAutoplayAudio: any; /** * Number of subjects introduced to the user during lessons before quizzing. * @type {number} * @memberof UserPreferences */ lessonsBatchSize: any; /** * The order in which lessons are presented. The options are ascending_level_then_subject, shuffled, and ascending_level_then_shuffled. The default (and best experience) is ascending_level_then_subject. * @type {string} * @memberof UserPreferences */ lessonsPresentationOrder: UserPreferencesLessonsPresentationOrderEnum; /** * Automatically play pronunciation audio for vocabulary during reviews. * @type {boolean} * @memberof UserPreferences */ reviewsAutoplayAudio: any; /** * Toggle for display SRS change indicator after a subject has been completely answered during review. * @type {boolean} * @memberof UserPreferences */ reviewsDisplaySrsIndicator: any; } /** * @export * @enum {string} */ export enum UserPreferencesLessonsPresentationOrderEnum { AscendingLevelThenSubject = 'ascending_level_then_subject', Shuffled = 'shuffled', AscendingLevelThenShuffled = 'ascending_level_then_shuffled' }
dogboydog/wanikani-cli
models/reset-data.ts
<filename>models/reset-data.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface ResetData */ export interface ResetData { /** * Timestamp when the user confirmed the reset. * @type {Date} * @memberof ResetData */ confirmedAt: any | null; /** * Timestamp when the reset was created. * @type {Date} * @memberof ResetData */ createdAt: any; /** * The user's level before the reset, from 1 to 60 * @type {number} * @memberof ResetData */ originalLevel: any; /** * The user's level after the reset, from 1 to 60. It must be less than or equal to original_level. * @type {number} * @memberof ResetData */ targetLevel: any; }
dogboydog/wanikani-cli
models/base-collection-pages.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface BaseCollectionPages */ export interface BaseCollectionPages { /** * * @type {string} * @memberof BaseCollectionPages */ nextUrl: any | null; /** * * @type {string} * @memberof BaseCollectionPages */ previousUrl: any | null; /** * * @type {number} * @memberof BaseCollectionPages */ perPage: any; }
dogboydog/wanikani-cli
models/auxiliary-meaning.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface AuxiliaryMeaning */ export interface AuxiliaryMeaning { /** * A singular subject meaning. * @type {string} * @memberof AuxiliaryMeaning */ meaning: any; /** * Either whitelist or blacklist. When evaluating user input, whitelisted meanings are used to match for correctness. Blacklisted meanings are used to match for incorrectness. * @type {string} * @memberof AuxiliaryMeaning */ type: any; }
dogboydog/wanikani-cli
models/radical-character-image.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface RadicalCharacterImage */ export interface RadicalCharacterImage { /** * The location of the image. * @type {string} * @memberof RadicalCharacterImage */ url: any; /** * The content type of the image. Currently the API delivers image/png and image/svg+xml. * @type {string} * @memberof RadicalCharacterImage */ contentType: any; /** * Details about the image. Each content_type returns a uniquely structured object. * @type {ImagePngMetadata | ImageSvgMetadata} * @memberof RadicalCharacterImage */ metadata: any; }
dogboydog/wanikani-cli
src/apis/assignment-api.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { Assignment } from '../../models'; import { Assignments } from '../../models'; import { BaseError } from '../../models'; import { StartAssignmentRequest } from '../../models'; import { SubjectType } from '../../models'; /** * AssignmentApi - axios parameter creator * @export */ export const AssignmentApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific assignment by its id. * @summary Get a Specific Assignment * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getAssignment: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getAssignment.'); } const localVarPath = `/assignments/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all assignments, ordered by ascending created_at, 500 at a time. * @summary Get All Assignments * @param {string} [availableAfter] Only assignments available at or after this time are returned. * @param {string} [availableBefore] Only assignments available at or before this time are returned. * @param {boolean} [burned] When set to true, returns assignments that have a value in data.burned_at. Returns assignments with a null data.burned_at if false. * @param {boolean} [hidden] Return assignments with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only assignments where data.id matches one of the array values are returned. * @param {boolean} [immediatelyAvailableForLessons] Returns assignments which are immediately available for lessons * @param {boolean} [immediatelyAvailableForReview] Returns assignments which are immediately available for review * @param {boolean} [inReview] Returns assignments which are in the review state * @param {Array&lt;number&gt;} [levels] Only assignments where the associated subject level matches one of the array values are returned. Valid values range from 1 to 60. * @param {Array&lt;number&gt;} [srsStages] Only assignments where data.srs_stage matches one of the array values are returned. Valid values range from 0 to 9 * @param {boolean} [started] When set to true, returns assignments that have a value in data.started_at. Returns assignments with a null data.started_at if false. * @param {Array&lt;number&gt;} [subjectIds] Only assignments where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only assignments where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {boolean} [unlocked] When set to true, returns assignments that have a value in data.unlocked_at. Returns assignments with a null data.unlocked_at if false. * @param {string} [updatedAfter] Only assignments updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getAssignments: async (availableAfter?: string, availableBefore?: string, burned?: boolean, hidden?: boolean, ids?: Array<number>, immediatelyAvailableForLessons?: boolean, immediatelyAvailableForReview?: boolean, inReview?: boolean, levels?: Array<number>, srsStages?: Array<number>, started?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, unlocked?: boolean, updatedAfter?: string, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/assignments`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (availableAfter !== undefined) { localVarQueryParameter['available_after'] = (availableAfter as any instanceof Date) ? (availableAfter as any).toISOString().substr(0,10) : availableAfter; } if (availableBefore !== undefined) { localVarQueryParameter['available_before'] = (availableBefore as any instanceof Date) ? (availableBefore as any).toISOString().substr(0,10) : availableBefore; } if (burned !== undefined) { localVarQueryParameter['burned'] = burned; } if (hidden !== undefined) { localVarQueryParameter['hidden'] = hidden; } if (ids) { localVarQueryParameter['ids'] = ids; } if (immediatelyAvailableForLessons !== undefined) { localVarQueryParameter['immediately_available_for_lessons'] = immediatelyAvailableForLessons; } if (immediatelyAvailableForReview !== undefined) { localVarQueryParameter['immediately_available_for_review'] = immediatelyAvailableForReview; } if (inReview !== undefined) { localVarQueryParameter['in_review'] = inReview; } if (levels) { localVarQueryParameter['levels'] = levels; } if (srsStages) { localVarQueryParameter['srs_stages'] = srsStages; } if (started !== undefined) { localVarQueryParameter['started'] = started; } if (subjectIds) { localVarQueryParameter['subject_ids'] = subjectIds; } if (subjectTypes) { localVarQueryParameter['subject_types'] = subjectTypes; } if (unlocked !== undefined) { localVarQueryParameter['unlocked'] = unlocked; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Mark the assignment as started, moving the assignment from the lessons queue to the review queue. Returns the updated assignment. * @summary Start an Assignment * @param {number} id ID of the resource * @param {StartAssignmentRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ startAssignment: async (id: number, body?: StartAssignmentRequest, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling startAssignment.'); } const localVarPath = `/assignments/{id}/start` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required localVarHeaderParameter['Content-Type'] = 'application/json'; const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * AssignmentApi - functional programming interface * @export */ export const AssignmentApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific assignment by its id. * @summary Get a Specific Assignment * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getAssignment(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Assignment>> { const localVarAxiosArgs = await AssignmentApiAxiosParamCreator(configuration).getAssignment(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all assignments, ordered by ascending created_at, 500 at a time. * @summary Get All Assignments * @param {string} [availableAfter] Only assignments available at or after this time are returned. * @param {string} [availableBefore] Only assignments available at or before this time are returned. * @param {boolean} [burned] When set to true, returns assignments that have a value in data.burned_at. Returns assignments with a null data.burned_at if false. * @param {boolean} [hidden] Return assignments with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only assignments where data.id matches one of the array values are returned. * @param {boolean} [immediatelyAvailableForLessons] Returns assignments which are immediately available for lessons * @param {boolean} [immediatelyAvailableForReview] Returns assignments which are immediately available for review * @param {boolean} [inReview] Returns assignments which are in the review state * @param {Array&lt;number&gt;} [levels] Only assignments where the associated subject level matches one of the array values are returned. Valid values range from 1 to 60. * @param {Array&lt;number&gt;} [srsStages] Only assignments where data.srs_stage matches one of the array values are returned. Valid values range from 0 to 9 * @param {boolean} [started] When set to true, returns assignments that have a value in data.started_at. Returns assignments with a null data.started_at if false. * @param {Array&lt;number&gt;} [subjectIds] Only assignments where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only assignments where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {boolean} [unlocked] When set to true, returns assignments that have a value in data.unlocked_at. Returns assignments with a null data.unlocked_at if false. * @param {string} [updatedAfter] Only assignments updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getAssignments(availableAfter?: string, availableBefore?: string, burned?: boolean, hidden?: boolean, ids?: Array<number>, immediatelyAvailableForLessons?: boolean, immediatelyAvailableForReview?: boolean, inReview?: boolean, levels?: Array<number>, srsStages?: Array<number>, started?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, unlocked?: boolean, updatedAfter?: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Assignments>> { const localVarAxiosArgs = await AssignmentApiAxiosParamCreator(configuration).getAssignments(availableAfter, availableBefore, burned, hidden, ids, immediatelyAvailableForLessons, immediatelyAvailableForReview, inReview, levels, srsStages, started, subjectIds, subjectTypes, unlocked, updatedAfter, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Mark the assignment as started, moving the assignment from the lessons queue to the review queue. Returns the updated assignment. * @summary Start an Assignment * @param {number} id ID of the resource * @param {StartAssignmentRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async startAssignment(id: number, body?: StartAssignmentRequest, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Assignment>> { const localVarAxiosArgs = await AssignmentApiAxiosParamCreator(configuration).startAssignment(id, body, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * AssignmentApi - factory interface * @export */ export const AssignmentApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific assignment by its id. * @summary Get a Specific Assignment * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getAssignment(id: number, options?: any): AxiosPromise<Assignment> { return AssignmentApiFp(configuration).getAssignment(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all assignments, ordered by ascending created_at, 500 at a time. * @summary Get All Assignments * @param {string} [availableAfter] Only assignments available at or after this time are returned. * @param {string} [availableBefore] Only assignments available at or before this time are returned. * @param {boolean} [burned] When set to true, returns assignments that have a value in data.burned_at. Returns assignments with a null data.burned_at if false. * @param {boolean} [hidden] Return assignments with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only assignments where data.id matches one of the array values are returned. * @param {boolean} [immediatelyAvailableForLessons] Returns assignments which are immediately available for lessons * @param {boolean} [immediatelyAvailableForReview] Returns assignments which are immediately available for review * @param {boolean} [inReview] Returns assignments which are in the review state * @param {Array&lt;number&gt;} [levels] Only assignments where the associated subject level matches one of the array values are returned. Valid values range from 1 to 60. * @param {Array&lt;number&gt;} [srsStages] Only assignments where data.srs_stage matches one of the array values are returned. Valid values range from 0 to 9 * @param {boolean} [started] When set to true, returns assignments that have a value in data.started_at. Returns assignments with a null data.started_at if false. * @param {Array&lt;number&gt;} [subjectIds] Only assignments where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only assignments where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {boolean} [unlocked] When set to true, returns assignments that have a value in data.unlocked_at. Returns assignments with a null data.unlocked_at if false. * @param {string} [updatedAfter] Only assignments updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getAssignments(availableAfter?: string, availableBefore?: string, burned?: boolean, hidden?: boolean, ids?: Array<number>, immediatelyAvailableForLessons?: boolean, immediatelyAvailableForReview?: boolean, inReview?: boolean, levels?: Array<number>, srsStages?: Array<number>, started?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, unlocked?: boolean, updatedAfter?: string, options?: any): AxiosPromise<Assignments> { return AssignmentApiFp(configuration).getAssignments(availableAfter, availableBefore, burned, hidden, ids, immediatelyAvailableForLessons, immediatelyAvailableForReview, inReview, levels, srsStages, started, subjectIds, subjectTypes, unlocked, updatedAfter, options).then((request) => request(axios, basePath)); }, /** * Mark the assignment as started, moving the assignment from the lessons queue to the review queue. Returns the updated assignment. * @summary Start an Assignment * @param {number} id ID of the resource * @param {StartAssignmentRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} */ startAssignment(id: number, body?: StartAssignmentRequest, options?: any): AxiosPromise<Assignment> { return AssignmentApiFp(configuration).startAssignment(id, body, options).then((request) => request(axios, basePath)); }, }; }; /** * AssignmentApi - object-oriented interface * @export * @class AssignmentApi * @extends {BaseAPI} */ export class AssignmentApi extends BaseAPI { /** * Retrieves a specific assignment by its id. * @summary Get a Specific Assignment * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AssignmentApi */ public getAssignment(id: number, options?: any) { return AssignmentApiFp(this.configuration).getAssignment(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all assignments, ordered by ascending created_at, 500 at a time. * @summary Get All Assignments * @param {string} [availableAfter] Only assignments available at or after this time are returned. * @param {string} [availableBefore] Only assignments available at or before this time are returned. * @param {boolean} [burned] When set to true, returns assignments that have a value in data.burned_at. Returns assignments with a null data.burned_at if false. * @param {boolean} [hidden] Return assignments with a matching value in the hidden attribute * @param {Array&lt;number&gt;} [ids] Only assignments where data.id matches one of the array values are returned. * @param {boolean} [immediatelyAvailableForLessons] Returns assignments which are immediately available for lessons * @param {boolean} [immediatelyAvailableForReview] Returns assignments which are immediately available for review * @param {boolean} [inReview] Returns assignments which are in the review state * @param {Array&lt;number&gt;} [levels] Only assignments where the associated subject level matches one of the array values are returned. Valid values range from 1 to 60. * @param {Array&lt;number&gt;} [srsStages] Only assignments where data.srs_stage matches one of the array values are returned. Valid values range from 0 to 9 * @param {boolean} [started] When set to true, returns assignments that have a value in data.started_at. Returns assignments with a null data.started_at if false. * @param {Array&lt;number&gt;} [subjectIds] Only assignments where data.subject_id matches one of the array values are returned. * @param {Array&lt;SubjectType&gt;} [subjectTypes] Only assignments where data.subject_type matches one of the array values are returned. Valid values are: radical, kanji, or vocabulary. * @param {boolean} [unlocked] When set to true, returns assignments that have a value in data.unlocked_at. Returns assignments with a null data.unlocked_at if false. * @param {string} [updatedAfter] Only assignments updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AssignmentApi */ public getAssignments(availableAfter?: string, availableBefore?: string, burned?: boolean, hidden?: boolean, ids?: Array<number>, immediatelyAvailableForLessons?: boolean, immediatelyAvailableForReview?: boolean, inReview?: boolean, levels?: Array<number>, srsStages?: Array<number>, started?: boolean, subjectIds?: Array<number>, subjectTypes?: Array<SubjectType>, unlocked?: boolean, updatedAfter?: string, options?: any) { return AssignmentApiFp(this.configuration).getAssignments(availableAfter, availableBefore, burned, hidden, ids, immediatelyAvailableForLessons, immediatelyAvailableForReview, inReview, levels, srsStages, started, subjectIds, subjectTypes, unlocked, updatedAfter, options).then((request) => request(this.axios, this.basePath)); } /** * Mark the assignment as started, moving the assignment from the lessons queue to the review queue. Returns the updated assignment. * @summary Start an Assignment * @param {number} id ID of the resource * @param {StartAssignmentRequest} [body] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AssignmentApi */ public startAssignment(id: number, body?: StartAssignmentRequest, options?: any) { return AssignmentApiFp(this.configuration).startAssignment(id, body, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
models/vocab-subject.ts
<filename>models/vocab-subject.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {CommonSubject} from './common-subject'; /** * * @export * @interface VocabSubject */ export interface VocabSubject extends CommonSubject { /** * An array of numeric identifiers for the kanji that make up this vocabulary. Note that these are the subjects that must be have passed assignments in order to unlock this subject's assignment. * @type {Array&lt;number&gt;} * @memberof VocabSubject */ componentSubjectIds: any; /** * A collection of context sentences. See table below for the object structure. * @type {Array&lt;ContextSentence&gt;} * @memberof VocabSubject */ contextSentences: any; /** * The subject's meaning mnemonic. * @type {string} * @memberof VocabSubject */ meaningMnemonic: any; /** * Parts of speech. * @type {Array&lt;string&gt;} * @memberof VocabSubject */ partsOfSpeech: any; /** * A collection of pronunciation audio. See table below for the object structure. * @type {Array&lt;PronunciationAudio&gt;} * @memberof VocabSubject */ pronunciationAudios: any; /** * Selected readings for the vocabulary. See table below for the object structure. * @type {Array&lt;VocabReading&gt;} * @memberof VocabSubject */ readings: any; /** * The subject's reading mnemonic. * @type {string} * @memberof VocabSubject */ readingMnemonic: any; }
dogboydog/wanikani-cli
models/study-materials.ts
<reponame>dogboydog/wanikani-cli<filename>models/study-materials.ts /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseCollection} from './base-collection'; /** * * @export * @interface StudyMaterials */ export interface StudyMaterials extends BaseCollection { /** * * @type {Array&lt;StudyMaterial&gt;} * @memberof StudyMaterials */ data: any; }
dogboydog/wanikani-cli
models/review-statistic-data.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface ReviewStatisticData */ export interface ReviewStatisticData { /** * Timestamp when the review statistic was created. * @type {Date} * @memberof ReviewStatisticData */ createdAt: any; /** * Indicates if the associated subject has been hidden, preventing it from appearing in lessons or reviews. * @type {boolean} * @memberof ReviewStatisticData */ hidden: any; /** * Total number of correct answers submitted for the meaning of the associated subject. * @type {number} * @memberof ReviewStatisticData */ meaningCorrect: any; /** * The current, uninterrupted series of correct answers given for the meaning of the associated subject. * @type {number} * @memberof ReviewStatisticData */ meaningCurrentStreak: any; /** * Total number of incorrect answers submitted for the meaning of the associated subject. * @type {number} * @memberof ReviewStatisticData */ meaningIncorrect: any; /** * The longest, uninterrupted series of correct answers ever given for the meaning of the associated subject. * @type {number} * @memberof ReviewStatisticData */ meaningMaxStreak: any; /** * The overall correct answer rate by the user for the subject, including both meaning and reading. * @type {number} * @memberof ReviewStatisticData */ percentageCorrect: any; /** * Total number of correct answers submitted for the reading of the associated subject. * @type {number} * @memberof ReviewStatisticData */ readingCorrect: any; /** * The current, uninterrupted series of correct answers given for the reading of the associated subject. * @type {number} * @memberof ReviewStatisticData */ readingCurrentStreak: any; /** * Total number of incorrect answers submitted for the reading of the associated subject. * @type {number} * @memberof ReviewStatisticData */ readingIncorrect: any; /** * The longest, uninterrupted series of correct answers ever given for the reading of the associated subject. * @type {number} * @memberof ReviewStatisticData */ readingMaxStreak: any; /** * Unique identifier of the associated subject. * @type {number} * @memberof ReviewStatisticData */ subjectId: any; /** * * @type {SubjectType} * @memberof ReviewStatisticData */ subjectType: any; }
dogboydog/wanikani-cli
models/spaced-repetition-system-data.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface SpacedRepetitionSystemData */ export interface SpacedRepetitionSystemData { /** * position of the burning stage. * @type {number} * @memberof SpacedRepetitionSystemData */ burningStagePosition: any; /** * Timestamp when the spaced_repetition_system was created. * @type {Date} * @memberof SpacedRepetitionSystemData */ createdAt: any; /** * Details about the spaced repetition system. * @type {string} * @memberof SpacedRepetitionSystemData */ description: any; /** * The name of the spaced repetition system * @type {string} * @memberof SpacedRepetitionSystemData */ name: any; /** * position of the passing stage. * @type {number} * @memberof SpacedRepetitionSystemData */ passingStagePosition: any; /** * A collection of stages. See table below for the object structure. * @type {Array&lt;StageAttributes&gt;} * @memberof SpacedRepetitionSystemData */ stages: any; /** * position of the starting stage. * @type {number} * @memberof SpacedRepetitionSystemData */ startingStagePosition: any; /** * position of the unlocking stage. * @type {number} * @memberof SpacedRepetitionSystemData */ unlockingStagePosition: any; }
dogboydog/wanikani-cli
src/cli/list/list.definition.ts
<filename>src/cli/list/list.definition.ts /* * This program and the accompanying materials are made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-v20.html * * SPDX-License-Identifier: EPL-2.0 * * Copyright Contributors to the Zowe Project. * */ import { ICommandDefinition } from "@zowe/imperative"; import {CommonOptions} from "../common-options"; import { ListReviewsDefinition } from "./reviews/list-reviews.definition"; /** * This object defines the top level command group for zosfiles. This is not * something that is intended to be used outside of this npm package. * * @private */ const definition: ICommandDefinition = { name: "list", aliases: ["ls"], type: "group", summary: "List different details about your studies", description: "List different details about your studies", children: [ ListReviewsDefinition ], passOn: [ { property: "options", value: [ CommonOptions.TOKEN_OPTION ], ignoreNodes: [{ type: 'group' // don't put the token option on commands that only have children }] } ] }; export = definition;
dogboydog/wanikani-cli
models/spaced-repetition-systems.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseCollection} from './base-collection'; /** * * @export * @interface SpacedRepetitionSystems */ export interface SpacedRepetitionSystems extends BaseCollection { /** * * @type {Array&lt;SpacedRepetitionSystem&gt;} * @memberof SpacedRepetitionSystems */ data: any; }
dogboydog/wanikani-cli
models/kanji-reading.ts
<reponame>dogboydog/wanikani-cli /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseReading} from './base-reading'; /** * * @export * @interface KanjiReading */ export interface KanjiReading extends BaseReading { /** * The kanji reading's classfication: kunyomi, nanori, or onyomi. * @type {string} * @memberof KanjiReading */ type: KanjiReadingTypeEnum; } /** * @export * @enum {string} */ export enum KanjiReadingTypeEnum { Kunyomi = 'kunyomi', Nanori = 'nanori', Onyomi = 'onyomi' }
dogboydog/wanikani-cli
models/resource-object-type.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @enum {string} */ export enum ResourceObjectType { Assignment = 'assignment', Kanji = 'kanji', LevelProgression = 'level_progression', Radical = 'radical', Reset = 'reset', ReviewStatistic = 'review_statistic', Review = 'review', SpacedRepetitionSystem = 'spaced_repetition_system', StudyMaterial = 'study_material', User = 'user', Vocabulary = 'vocabulary' }
dogboydog/wanikani-cli
models/study-material.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import {BaseResource} from './base-resource'; /** * * @export * @interface StudyMaterial */ export interface StudyMaterial extends BaseResource { /** * * @type {StudyMaterialData} * @memberof StudyMaterial */ data: any; }
dogboydog/wanikani-cli
models/image-svg-metadata.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface ImageSvgMetadata */ export interface ImageSvgMetadata { /** * The SVG asset contains built-in CSS styling * @type {boolean} * @memberof ImageSvgMetadata */ inlineStyles: any; }
dogboydog/wanikani-cli
models/create-review-response-resources-updated.ts
<gh_stars>1-10 /* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ /** * * @export * @interface CreateReviewResponseResourcesUpdated */ export interface CreateReviewResponseResourcesUpdated { /** * * @type {Assignment} * @memberof CreateReviewResponseResourcesUpdated */ assignment: any; /** * * @type {ReviewStatistic} * @memberof CreateReviewResponseResourcesUpdated */ reviewStatistic: any; }
dogboydog/wanikani-cli
src/apis/reset-api.ts
/* tslint:disable */ /* eslint-disable */ /** * WaniKani * WaniKani: The API * * OpenAPI spec version: 20170710.0 * * */ import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; import { Configuration } from '../../configuration'; // Some imports not used depending on template conditions // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; import { BaseError } from '../../models'; import { Reset } from '../../models'; import { Resets } from '../../models'; /** * ResetApi - axios parameter creator * @export */ export const ResetApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * Retrieves a specific reset by its id. * @summary Get a Specific Reset * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReset: async (id: number, options: any = {}): Promise<RequestArgs> => { // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new RequiredError('id','Required parameter id was null or undefined when calling getReset.'); } const localVarPath = `/resets/{id}` .replace(`{${"id"}}`, encodeURIComponent(String(id))); // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, /** * Returns a collection of all resets, ordered by ascending created_at, 500 at a time. * @summary Get All Resets * @param {Array&lt;number&gt;} [ids] Only resets where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only resets updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getResets: async (ids?: Array<number>, updatedAfter?: string, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/resets`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, 'https://example.com'); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; // authentication bearerAuth required if (ids) { localVarQueryParameter['ids'] = ids; } if (updatedAfter !== undefined) { localVarQueryParameter['updated_after'] = (updatedAfter as any instanceof Date) ? (updatedAfter as any).toISOString().substr(0,10) : updatedAfter; } const query = new URLSearchParams(localVarUrlObj.search); for (const key in localVarQueryParameter) { query.set(key, localVarQueryParameter[key]); } for (const key in options.query) { query.set(key, options.query[key]); } localVarUrlObj.search = (new URLSearchParams(query)).toString(); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: localVarUrlObj.pathname + localVarUrlObj.search + localVarUrlObj.hash, options: localVarRequestOptions, }; }, } }; /** * ResetApi - functional programming interface * @export */ export const ResetApiFp = function(configuration?: Configuration) { return { /** * Retrieves a specific reset by its id. * @summary Get a Specific Reset * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getReset(id: number, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Reset>> { const localVarAxiosArgs = await ResetApiAxiosParamCreator(configuration).getReset(id, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, /** * Returns a collection of all resets, ordered by ascending created_at, 500 at a time. * @summary Get All Resets * @param {Array&lt;number&gt;} [ids] Only resets where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only resets updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getResets(ids?: Array<number>, updatedAfter?: string, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Resets>> { const localVarAxiosArgs = await ResetApiAxiosParamCreator(configuration).getResets(ids, updatedAfter, options); return (axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { const axiosRequestArgs = {...localVarAxiosArgs.options, url: basePath + localVarAxiosArgs.url}; return axios.request(axiosRequestArgs); }; }, } }; /** * ResetApi - factory interface * @export */ export const ResetApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { return { /** * Retrieves a specific reset by its id. * @summary Get a Specific Reset * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} */ getReset(id: number, options?: any): AxiosPromise<Reset> { return ResetApiFp(configuration).getReset(id, options).then((request) => request(axios, basePath)); }, /** * Returns a collection of all resets, ordered by ascending created_at, 500 at a time. * @summary Get All Resets * @param {Array&lt;number&gt;} [ids] Only resets where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only resets updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ getResets(ids?: Array<number>, updatedAfter?: string, options?: any): AxiosPromise<Resets> { return ResetApiFp(configuration).getResets(ids, updatedAfter, options).then((request) => request(axios, basePath)); }, }; }; /** * ResetApi - object-oriented interface * @export * @class ResetApi * @extends {BaseAPI} */ export class ResetApi extends BaseAPI { /** * Retrieves a specific reset by its id. * @summary Get a Specific Reset * @param {number} id ID of the resource * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResetApi */ public getReset(id: number, options?: any) { return ResetApiFp(this.configuration).getReset(id, options).then((request) => request(this.axios, this.basePath)); } /** * Returns a collection of all resets, ordered by ascending created_at, 500 at a time. * @summary Get All Resets * @param {Array&lt;number&gt;} [ids] Only resets where data.id matches one of the array values are returned. * @param {string} [updatedAfter] Only resets updated after this time are returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof ResetApi */ public getResets(ids?: Array<number>, updatedAfter?: string, options?: any) { return ResetApiFp(this.configuration).getResets(ids, updatedAfter, options).then((request) => request(this.axios, this.basePath)); } }
dogboydog/wanikani-cli
src/cli/wanikani-request.ts
import axios, { AxiosResponse } from 'axios'; import {ICommandArguments} from '@zowe/imperative'; import {RequestArgs} from '../apis/base'; export class WaniKaniRequest{ public static async makeRequest(request: RequestArgs, args: ICommandArguments): Promise<AxiosResponse>{ const client = axios.create({ baseURL: 'https://api.wanikani.com/v2/' , timeout: 10000, headers: {'Authorization': `Bearer ${args.token}`} }); return client.request(request); } }