From 260dbee9e28928b05d4d35bf919de4959acff9f7 Mon Sep 17 00:00:00 2001 From: Tom Wanzek Date: Wed, 31 Aug 2016 22:13:13 -0400 Subject: [PATCH] d3-dsv and d3-request * d3-dsv: Added new definitions and tests correspondinf to d3-dsv module (v 1.0.1) of D3 version 4. Moved legacy definitions and tests into new sub folder v0. These are no longer relevant, as they do not reflect d3-dsv package at all. There should be no dependencies on them. * d3-request: Added definitions for module and related shape tests. --- d3-dsv/d3-dsv-tests.ts | 317 +++++++++++++++++++++- d3-dsv/index.d.ts | 121 +++++---- d3-dsv/v0/d3-dsv-tests.ts | 8 + d3-dsv/v0/index.d.ts | 65 +++++ d3-request/d3-request-tests.ts | 470 +++++++++++++++++++++++++++++++++ d3-request/index.d.ts | 84 ++++++ d3-request/tsconfig.json | 19 ++ 7 files changed, 1029 insertions(+), 55 deletions(-) create mode 100644 d3-dsv/v0/d3-dsv-tests.ts create mode 100644 d3-dsv/v0/index.d.ts create mode 100644 d3-request/d3-request-tests.ts create mode 100644 d3-request/index.d.ts create mode 100644 d3-request/tsconfig.json diff --git a/d3-dsv/d3-dsv-tests.ts b/d3-dsv/d3-dsv-tests.ts index 587d4d5a55..40516166b1 100644 --- a/d3-dsv/d3-dsv-tests.ts +++ b/d3-dsv/d3-dsv-tests.ts @@ -1,8 +1,319 @@ +/** + * Typescript definition tests for d3/d3-dsv module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3Dsv from 'd3-dsv'; + +// ------------------------------------------------------------------------------------------ +// Preperatory Steps +// ------------------------------------------------------------------------------------------ -import d3dsv = require("d3-dsv"); +let csvTestString: string = '1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +let tsvTestString: string = '1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +let pipedTestString: string = '1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; -var csv = d3dsv(","); +let csvTestStringWithHeader: string = 'Year,Make,Model,Length\n1997,Ford,E350,2.34\n2000,Mercury,Cougar,2.38'; +let tsvTestStringWithHeader: string = 'Year\tMake\tModel\tLength\n1997\tFord\tE350\t2.34\n2000\tMercury\tCougar\t2.38'; +let pipedTestStringWithHeader: string = 'Year|Make|Model|Length\n1997|Ford|E350|2.34\n2000|Mercury|Cougar|2.38'; -var rows = csv.parse("a,b,c\n1,2,3\n4,5,6"); +interface ParsedTestObject { + year: Date; + make: string; + model: string; + length: number; +} +let parseArray: d3Dsv.DSVParsedArray; +let parseMappedArray: d3Dsv.DSVParsedArray; + +let parseRowsArray: Array>; +let parseRowsMappedArray: Array; + + +let columns: Array; +let num: number; +let date: Date; +let str: string; + +// ------------------------------------------------------------------------------------------ +// Test CSV +// ------------------------------------------------------------------------------------------ + +// csvParse(...) ============================================================================ + +// without row mapper ----------------------------------------------------------------------- + +parseArray = d3Dsv.csvParse(csvTestStringWithHeader); + +columns = parseArray.columns; + +str = parseArray[0]['Year']; +// date = parseArray[0]['Year']; // fails, return value is string + +// with row mapper --------------------------------------------------------------------------- + +parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, function (rawRow, index, columns) { + let rr: d3Dsv.DSVRowString = rawRow; + let i: number = index; + let c: Array = columns; + let pr: ParsedTestObject; + + pr = { + year: new Date(+rr['Year'], 0, 1), + make: rr['Make'], + model: rr['Model'], + length: +rr['Length'] + }; + + return pr; + +}); + +columns = parseMappedArray.columns; + +date = parseMappedArray[0].year; +str = parseMappedArray[0].make; +str = parseMappedArray[0].model; +num = parseMappedArray[0].length; + + +// csvParseRows(...) ============================================================================ + +// without row mapper ----------------------------------------------------------------------- + +parseRowsArray = d3Dsv.csvParseRows(csvTestString); + + +str = parseRowsArray[0][0]; // 'Year' of first row +// date = parseRowsArray[0][0]; // fails, return value is string + +// with row mapper --------------------------------------------------------------------------- + +parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, function (rawRow, index) { + let rr: Array = rawRow; + let i: number = index; + let pr: ParsedTestObject; + + pr = { + year: new Date(+rr[0], 0, 1), + make: rr[1], + model: rr[2], + length: +rr[3] + }; + + return pr; + +}); + +date = parseRowsMappedArray[0].year; +str = parseRowsMappedArray[0].make; +str = parseRowsMappedArray[0].model; +num = parseRowsMappedArray[0].length; + +// csvFormat(...) ============================================================================ + +str = d3Dsv.csvFormat(parseRowsMappedArray); +str = d3Dsv.csvFormat(parseRowsMappedArray, columns); + +// csvFormatRows(...) ======================================================================== + +str = d3Dsv.csvFormatRows(parseRowsMappedArray.map(function(d, i) { + return [ + d.year.getFullYear().toString(), + d.make, + d.model, + d.length.toString() + ]; +})); + +// ------------------------------------------------------------------------------------------ +// Test TSV +// ------------------------------------------------------------------------------------------ + +// tsvParse(...) ============================================================================ + +// without row mapper ----------------------------------------------------------------------- + +parseArray = d3Dsv.tsvParse(tsvTestStringWithHeader); + +columns = parseArray.columns; + +str = parseArray[0]['Year']; +// date = parseArray[0]['Year']; // fails, return value is string + +// with row mapper --------------------------------------------------------------------------- + +parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, function (rawRow, index, columns) { + let rr: d3Dsv.DSVRowString = rawRow; + let i: number = index; + let c: Array = columns; + let pr: ParsedTestObject; + + pr = { + year: new Date(+rr['Year'], 0, 1), + make: rr['Make'], + model: rr['Model'], + length: +rr['Length'] + }; + + return pr; + +}); + +columns = parseMappedArray.columns; + +date = parseMappedArray[0].year; +str = parseMappedArray[0].make; +str = parseMappedArray[0].model; +num = parseMappedArray[0].length; + + +// tsvParseRows(...) ============================================================================ + +// without row mapper ----------------------------------------------------------------------- + +parseRowsArray = d3Dsv.tsvParseRows(tsvTestString); + + +str = parseRowsArray[0][0]; // 'Year' of first row +// date = parseRowsArray[0][0]; // fails, return value is string + +// with row mapper --------------------------------------------------------------------------- + +parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, function (rawRow, index) { + let rr: Array = rawRow; + let i: number = index; + let pr: ParsedTestObject; + + pr = { + year: new Date(+rr[0], 0, 1), + make: rr[1], + model: rr[2], + length: +rr[3] + }; + + return pr; + +}); + +date = parseRowsMappedArray[0].year; +str = parseRowsMappedArray[0].make; +str = parseRowsMappedArray[0].model; +num = parseRowsMappedArray[0].length; + +// tsvFormat(...) ============================================================================ + +str = d3Dsv.tsvFormat(parseRowsMappedArray); +str = d3Dsv.tsvFormat(parseRowsMappedArray, columns); + +// tsvFormatRows(...) ======================================================================== + +str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map(function(d, i) { + return [ + d.year.getFullYear().toString(), + d.make, + d.model, + d.length.toString() + ]; +})); + +// ------------------------------------------------------------------------------------------ +// Test DSV Generalized Parsers and Formatters +// ------------------------------------------------------------------------------------------ + +// Create custom-delimited Parser/Formatter ================================================= + +let dsv: d3Dsv.DSV; +dsv = d3Dsv.dsvFormat('|'); + +// parse(...) ============================================================================ + +// without row mapper ----------------------------------------------------------------------- + +parseArray = dsv.parse(pipedTestStringWithHeader); + +columns = parseArray.columns; + +str = parseArray[0]['Year']; +// date = parseArray[0]['Year']; // fails, return value is string + +// with row mapper --------------------------------------------------------------------------- + +parseMappedArray = dsv.parse(pipedTestStringWithHeader, function (rawRow, index, columns) { + let rr: d3Dsv.DSVRowString = rawRow; + let i: number = index; + let c: Array = columns; + let pr: ParsedTestObject; + + pr = { + year: new Date(+rr['Year'], 0, 1), + make: rr['Make'], + model: rr['Model'], + length: +rr['Length'] + }; + + return pr; + +}); + +columns = parseMappedArray.columns; + +date = parseMappedArray[0].year; +str = parseMappedArray[0].make; +str = parseMappedArray[0].model; +num = parseMappedArray[0].length; + + +// parseRows(...) ============================================================================ + +// without row mapper ----------------------------------------------------------------------- + +parseRowsArray = dsv.parseRows(pipedTestString); + + +str = parseRowsArray[0][0]; // 'Year' of first row +// date = parseRowsArray[0][0]; // fails, return value is string + +// with row mapper --------------------------------------------------------------------------- + +parseRowsMappedArray = dsv.parseRows(pipedTestString, function (rawRow, index) { + let rr: Array = rawRow; + let i: number = index; + let pr: ParsedTestObject; + + pr = { + year: new Date(+rr[0], 0, 1), + make: rr[1], + model: rr[2], + length: +rr[3] + }; + + return pr; + +}); + +date = parseRowsMappedArray[0].year; +str = parseRowsMappedArray[0].make; +str = parseRowsMappedArray[0].model; +num = parseRowsMappedArray[0].length; + +// format(...) ============================================================================ + +str = dsv.format(parseRowsMappedArray); +str = dsv.format(parseRowsMappedArray, columns); + +// formatRows(...) ======================================================================== + +str = dsv.formatRows(parseRowsMappedArray.map(function(d, i) { + return [ + d.year.getFullYear().toString(), + d.make, + d.model, + d.length.toString() + ]; +})); diff --git a/d3-dsv/index.d.ts b/d3-dsv/index.d.ts index b798c4fcbe..7682644987 100644 --- a/d3-dsv/index.d.ts +++ b/d3-dsv/index.d.ts @@ -1,65 +1,82 @@ -// Type definitions for d3-dsv -// Project: https://www.npmjs.com/package/d3-dsv -// Definitions by: Jason Swearingen +// Type definitions for D3JS d3-dsv module v1.0.1 +// Project: https://github.com/d3/d3-dsv/ +// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// ------------------------------------------------------------------------------------------ +// Shared Types and Interfaces +// ------------------------------------------------------------------------------------------ - /** A parser and formatter for DSV (CSV and TSV) files. -Extracted from D3. */ -declare var loader: ( - /** the symbol used to seperate cells in the row.*/ - delimiter: string, - /** example: "text/plain" */ - encoding?: string) => _d3dsv.D3Dsv; -export = loader; -export as namespace d3_dsv; +export interface DSVRowString { + [key: string]: string; +} -declare module _d3dsv { - /** A parser and formatter for DSV (CSV and TSV) files. -Extracted from D3. */ - export class D3Dsv { - /** Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows. - The string is assumed to be RFC4180-compliant. - Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names; - these column names become the attributes on the returned objects. - For example, consider the following CSV file: +export interface DSVRowAny { + [key: string]: any; +} -Year,Make,Model,Length -1997,Ford,E350,2.34 -2000,Mercury,Cougar,2.38 +export interface DSVParsedArray extends Array { + columns: Array; +} -The resulting JavaScript array is: +// ------------------------------------------------------------------------------------------ +// CSV Parsers and Formatters +// ------------------------------------------------------------------------------------------ -[ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"}, - {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ] - */ - public parse( - table: string, - /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */ - accessor?: (row: any) => TRow - ): TRow[]; - /** Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. The string is assumed to be RFC4180-compliant. Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file: +// csvParse(...) ============================================================================ -1997,Ford,E350,2.34 -2000,Mercury,Cougar,2.38 -The resulting JavaScript array is: +export function csvParse(csvString: string): DSVParsedArray; +export function csvParse(csvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DSVParsedArray; -[ ["1997", "Ford", "E350", "2.34"], - ["2000", "Mercury", "Cougar", "2.38"] ] -Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details.*/ - public parseRows( - table: string, - /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results.*/ - accessor?: (row: string[]) => TRow - ): TRow[]; - /** Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parse. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. +// csvParseRows(...) ======================================================================== -Each row should be an object, and all object properties will be converted into fields. For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. */ - public format(rows: any[]): string; - /** Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. */ - public formatRows(rows: any[]): string; +export function csvParseRows(csvString: string): Array>; +export function csvParseRows(csvString: string, row: (rawRow: Array, index: number) => ParsedRow): Array; +// csvFormat(...) ============================================================================ - } +export function csvFormat(rows: Array): string; +export function csvFormat(rows: Array, columns: Array): string; -} \ No newline at end of file +// csvFormatRows(...) ======================================================================== + +export function csvFormatRows(rows: Array>): string; + +// ------------------------------------------------------------------------------------------ +// TSV Parsers and Formatters +// ------------------------------------------------------------------------------------------ + +// tsvParse(...) ============================================================================ + +export function tsvParse(tsvString: string): DSVParsedArray; +export function tsvParse(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => MappedRow): DSVParsedArray; + +// tsvParseRows(...) ======================================================================== + +export function tsvParseRows(tsvString: string): Array>; +export function tsvParseRows(tsvString: string, row: (rawRow: Array, index: number) => MappedRow): Array; + +// tsvFormat(...) ============================================================================ + +export function tsvFormat(rows: Array): string; +export function tsvFormat(rows: Array, columns: Array): string; + +// tsvFormatRows(...) ======================================================================== + +export function tsvFormatRows(rows: Array>): string; + +// ------------------------------------------------------------------------------------------ +// DSV Generalized Parsers and Formatters +// ------------------------------------------------------------------------------------------ + +export interface DSV { + parse(dsvString: string): DSVParsedArray; + parse(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DSVParsedArray; + parseRows(dsvString: string): Array>; + parseRows(dsvString: string, row: (rawRow: Array, index: number) => ParsedRow): Array; + format(rows: Array): string; + format(rows: Array, columns: Array): string; + formatRows(rows: Array>): string; +} + +export function dsvFormat(delimiter: string): DSV; diff --git a/d3-dsv/v0/d3-dsv-tests.ts b/d3-dsv/v0/d3-dsv-tests.ts new file mode 100644 index 0000000000..587d4d5a55 --- /dev/null +++ b/d3-dsv/v0/d3-dsv-tests.ts @@ -0,0 +1,8 @@ + + +import d3dsv = require("d3-dsv"); + +var csv = d3dsv(","); + +var rows = csv.parse("a,b,c\n1,2,3\n4,5,6"); + diff --git a/d3-dsv/v0/index.d.ts b/d3-dsv/v0/index.d.ts new file mode 100644 index 0000000000..b798c4fcbe --- /dev/null +++ b/d3-dsv/v0/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for d3-dsv +// Project: https://www.npmjs.com/package/d3-dsv +// Definitions by: Jason Swearingen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + + /** A parser and formatter for DSV (CSV and TSV) files. +Extracted from D3. */ +declare var loader: ( + /** the symbol used to seperate cells in the row.*/ + delimiter: string, + /** example: "text/plain" */ + encoding?: string) => _d3dsv.D3Dsv; +export = loader; +export as namespace d3_dsv; + +declare module _d3dsv { + /** A parser and formatter for DSV (CSV and TSV) files. +Extracted from D3. */ + export class D3Dsv { + /** Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows. + The string is assumed to be RFC4180-compliant. + Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names; + these column names become the attributes on the returned objects. + For example, consider the following CSV file: + +Year,Make,Model,Length +1997,Ford,E350,2.34 +2000,Mercury,Cougar,2.38 + +The resulting JavaScript array is: + +[ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"}, + {"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ] + */ + public parse( + table: string, + /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */ + accessor?: (row: any) => TRow + ): TRow[]; + /** Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. The string is assumed to be RFC4180-compliant. Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file: + +1997,Ford,E350,2.34 +2000,Mercury,Cougar,2.38 +The resulting JavaScript array is: + +[ ["1997", "Ford", "E350", "2.34"], + ["2000", "Mercury", "Cougar", "2.38"] ] +Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details.*/ + public parseRows( + table: string, + /** coerce cells (strings) into different types or modify them. return null to strip this row from the output results.*/ + accessor?: (row: string[]) => TRow + ): TRow[]; + /** Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parse. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. + +Each row should be an object, and all object properties will be converted into fields. For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. */ + public format(rows: any[]): string; + /** Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. */ + public formatRows(rows: any[]): string; + + + } + +} \ No newline at end of file diff --git a/d3-request/d3-request-tests.ts b/d3-request/d3-request-tests.ts new file mode 100644 index 0000000000..798d200bd5 --- /dev/null +++ b/d3-request/d3-request-tests.ts @@ -0,0 +1,470 @@ +/** + * Typescript definition tests for d3/d3-request module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +// IMPORTANT: DO NOT ATTEMPT TO EXECUTE THE REQUESTS IN THIS TEST FILE +// THE URL AND PARAMETERIZATIONS ARE NOT VALID AS EXAMPLIFIED BELOW. + +import * as d3Request from 'd3-request'; +import { DSVParsedArray, DSVRowString } from 'd3-dsv'; + +// ------------------------------------------------------------------------------- +// Preparatory Steps +// ------------------------------------------------------------------------------- + +const url: string = 'http:// api.reddit.com'; + +interface RequestDatumGET { + kind: 'Listing'; +} + +interface ResponseDatumGET { + test: string; + value: number; +} + +interface RequestDatumPOST { + test: string; + value: number; +} + +interface ResponseDatumPOST { + success: boolean; +} + +let listenerXhr: (this: d3Request.Request, xhr: XMLHttpRequest) => void; + +let listenerProgress: (this: d3Request.Request, progEvent: ProgressEvent) => void; + +let listenerError: (this: d3Request.Request, error: any) => void; + +let listenerResult: (this: d3Request.Request, result: ResponseDatumGET[]) => void; + +// ------------------------------------------------------------------------------- +// Generic Request +// ------------------------------------------------------------------------------- + +// request to configure and send in follow-up +let request: d3Request.Request = d3Request.request(url); + +// GET-request with callback, immediately sent +let requestWithCallback: d3Request.Request = d3Request.request(url, function (error, xhr) { + let x: XMLHttpRequest; + if (!error) { + x = xhr; + console.log(xhr.responseText); + } +}); + + +// ------------------------------------------------------------------------------- +// Request interface +// ------------------------------------------------------------------------------- + +// Abort ----------------------------------------------------------------------- +let r1: d3Request.Request = request.abort(); + +// Get ------------------------------------------------------------------------- + +// no arguments +let r2: d3Request.Request = d3Request.request(url) + .get(); + +// with request datum +let r3: d3Request.Request = d3Request.request(url) + .get({ kind: 'Listing' }); + +// with callback for response handling +let r4: d3Request.Request = d3Request.request(url) + .response(xhr2Listing) + .get(function (error, response) { + let r: ResponseDatumGET[]; + if (!error) { + r = response; + console.log(r); + } + }); + +// with request datum and callback for response handling +let r5: d3Request.Request = d3Request.request(url) + .response(xhr2Listing) + .get({ kind: 'Listing' }, function (error, response) { + let r: ResponseDatumGET[]; + if (!error) { + r = response; + console.log(r); + } + }); + +// Headers -------------------------------------------------------------------- + +// get +let acceptEncoding: string = request.header('Accept-Encoding'); +// set +let r6: d3Request.Request = request.header('Accept-Encoding', 'gzip'); +// remove +let r7: d3Request.Request = request.header('Accept-Encoding', null); + +// Mime Type ------------------------------------------------------------------- + +// get +let mimeType: string = request.mimeType(); +// set +let r8: d3Request.Request = request.mimeType('application/json'); +// remove +let r9: d3Request.Request = request.mimeType(null); + +// Events - on ------------------------------------------------------------------ + +let r10: d3Request.Request = d3Request.request(url); + +// beforesent + +r10 = r10.on('beforesend', function (xhr) { + let that: d3Request.Request = this; + let x: XMLHttpRequest = xhr; + // do something; +}); + + +listenerXhr = r10.on('beforesend'); + + +// progress + +r10 = r10.on('progress', function (progEvent) { + let that: d3Request.Request = this; + let e: ProgressEvent = progEvent; + // do something; +}); + + +listenerProgress = r10.on('progress'); + + +// error + +r10 = r10.on('error', function (error) { + let that: d3Request.Request = this; + let err: any = error; + // do something; +}); + + +listenerError = r10.on('error'); + +// load + +r10 = r10.on('load', function (result) { + let that: d3Request.Request = this; + let res: ResponseDatumGET[] = result; + // do something; +}); + +r10 = r10.on('load', function (result: ResponseDatumGET[]) { + let that: d3Request.Request = this; + let res: ResponseDatumGET[] = result; + // do something; +}); + +// r10 = r10.on('load', function (result: number) { // fails, wrong argument type for callback +// let that: d3Request.Request = this; +// let res: number = result; +// // do something; +// }); + +listenerResult = r10.on('load'); + +// general (for unknown type additional event listener e.g. 'beforesent.custom' or 'load.custom') + +r10 = r10.on('progress.foo', function (progEvent: ProgressEvent) { + let that: d3Request.Request = this; + let e: any = ProgressEvent; + // do something; +}); + + +listenerProgress = r10.on('progress.foo'); + +r10 = r10.on('error.foo', function (error) { + let that: d3Request.Request = this; + let err: any = error; + // do something; +}); + + +listenerError = r10.on('error.foo'); + +// Password --------------------------------------------------------------------- + +// get +let password: string = request.password(); +// set +let r11: d3Request.Request = request.password('MyPassword'); + +// Post ------------------------------------------------------------------------- + +function xhr2Success(xhr: XMLHttpRequest): ResponseDatumPOST { + let result: ResponseDatumPOST; + + result = JSON.parse(xhr.responseText); + + return result; +} + +// no arguments +let r12: d3Request.Request = d3Request.request(url) + .post(); + +// with request datum +let r13: d3Request.Request = d3Request.request(url) + .post({ test: 'NewValue', value: 10 }); + +// with callback for response handling +let r14: d3Request.Request = d3Request.request(url).response(xhr2Success) + .post(function (error, response) { + let that: d3Request.Request = this; + let err: any = error; + let res: ResponseDatumPOST = response; + console.log('Success? ', res.success); + }); + +let r15: d3Request.Request = d3Request.request(url).response(xhr2Success) + .post({ test: 'NewValue', value: 10 }, function (error, response) { + let that: d3Request.Request = this; + let err: any = error; + let res: ResponseDatumPOST = response; + console.log('Success? ', res.success); + }); + +// Response --------------------------------------------------------------------- + +function xhr2Listing(xhr: XMLHttpRequest): ResponseDatumGET[] { + let result: ResponseDatumGET[]; + + result = JSON.parse(xhr.responseText); + + return result; +} + +let r16: d3Request.Request = d3Request.request(url) + .response>(xhr2Listing); + +// ResponseType ----------------------------------------------------------------- + +// get +let responseType: string = d3Request.request(url) + .responseType(); +// set +let r17: d3Request.Request = d3Request.request(url) + .responseType('application/json'); + +// Send ------------------------------------------------------------------------ + +// method only +let r18: d3Request.Request = d3Request.request(url) + .send('GET'); + +// method and request datum +let r19: d3Request.Request = d3Request.request(url) + .send('POST', { test: 'NewValue', value: 10 }); + +// method and callback for response handling +let r20: d3Request.Request = d3Request.request(url) + .response(xhr2Listing) + .send('GET', function (error, response) { + let r: ResponseDatumGET[]; + if (!error) { + r = response; + console.log(r); + } + }); + +// method,request datum and callback for response handling +let r21: d3Request.Request = d3Request.request(url) + .response(xhr2Listing) + .send('GET', { kind: 'Listing' }, function (error, response) { + let r: ResponseDatumGET[]; + if (!error) { + r = response; + console.log(r); + } + }); + + +// Timeout ----------------------------------------------------------------------- + +// get +let timeout: number = d3Request.request(url) + .timeout(); +// set +let r22: d3Request.Request = d3Request.request(url) + .timeout(500); + +// User---------------------------------------------------------------------------- + +// get +let user: string = request.user(); +// set +let r23: d3Request.Request = request.user('User'); + + +// ------------------------------------------------------------------------------- +// HTML Request +// ------------------------------------------------------------------------------- + + +let html: d3Request.Request = d3Request.html(url); +let htmlWithCallback: d3Request.Request = d3Request.html(url, function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: DocumentFragment = data; + console.log(d); +}); + + +// ------------------------------------------------------------------------------- +// JSON Request +// ------------------------------------------------------------------------------- + + +let json: d3Request.Request = d3Request.json(url); +let jsonWithCallback: d3Request.Request = d3Request.json(url, function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: ResponseDatumGET[] = data; + console.log(d); +}); + + + +// ------------------------------------------------------------------------------- +// Text Request +// ------------------------------------------------------------------------------- + +let text: d3Request.Request = d3Request.text(url); +let textWithCallback: d3Request.Request = d3Request.text(url, function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: string = data; + console.log(d); +}); + +// ------------------------------------------------------------------------------- +// XML Request +// ------------------------------------------------------------------------------- + +let xml: d3Request.Request = d3Request.xml(url); +let xmlWithCallback: d3Request.Request = d3Request.xml(url, function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: any = data; + console.log(d); +}); + + + +// ------------------------------------------------------------------------------- +// CSV Request +// ------------------------------------------------------------------------------- + +// url only +let csvRequest: d3Request.DsvRequest = d3Request.csv(url); + +// url and callback for response handling +let csvRequestWithCallback: d3Request.DsvRequest = d3Request.csv(url, function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: DSVParsedArray = data; + console.log(d); +}); + +// url, row mapping function and callback for response handling +let csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv(url, + function (rawRow, index, columns) { + let rr: DSVRowString = rawRow; + let i: number = index; + let cols: string[] = columns; + let mappedRow: ResponseDatumGET; + + mappedRow = { + test: rr['test'], + value: +rr['value'] + }; + + return mappedRow; + }, + function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: DSVParsedArray = data; + console.log(data); + }); + +// ------------------------------------------------------------------------------- +// TSV Request +// ------------------------------------------------------------------------------- + + +// url only +let tsvRequest: d3Request.DsvRequest = d3Request.tsv(url); + +// url and callback for response handling +let tsvRequestWithCallback: d3Request.DsvRequest = d3Request.tsv(url, function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: DSVParsedArray = data; + console.log(d); +}); + +// url, row mapping function and callback for response handling +let tsvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.tsv(url, + function (rawRow, index, columns) { + let rr: DSVRowString = rawRow; + let i: number = index; + let cols: string[] = columns; + let mappedRow: ResponseDatumGET; + + mappedRow = { + test: rr['test'], + value: +rr['value'] + }; + + return mappedRow; + }, + function (error, data) { + let that: d3Request.Request = this; + let err: any = error; + let d: DSVParsedArray = data; + console.log(data); + }); + +// ------------------------------------------------------------------------------- +// DsvRequest interface +// ------------------------------------------------------------------------------- + +// row(...) ---------------------------------------------------------------------- + +csvRequest = csvRequest + .row(function (rawRow, index, columns) { + let rr: DSVRowString = rawRow; + let i: number = index; + let cols: string[] = columns; + let mappedRow: ResponseDatumGET; + + mappedRow = { + test: rr['test'], + value: +rr['value'] + }; + + return mappedRow; + }); + +// inherited methods from Request interface --------------------------------------- + +// e.g. mimeType getter +mimeType = csvRequest.mimeType(); diff --git a/d3-request/index.d.ts b/d3-request/index.d.ts new file mode 100644 index 0000000000..2a0251a726 --- /dev/null +++ b/d3-request/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for D3JS d3-request module v1.0.2 +// Project: https://github.com/d3/d3-request/ +// Definitions by: Hugues Stefanski , Alex Ford , Boris Yankov , Tom Wanzek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { DSVParsedArray, DSVRowString, DSVRowAny } from 'd3-dsv'; + +export interface Request { + abort(): this; + + get(): this; + get(data: RequestData): this; + get(callback: (error: any, d: ResponseData) => void): this; + get(data: RequestData, callback: (error: any, d: ResponseData) => void): this; + + header(name: string): string; + header(name: string, value: string | null): this; + + mimeType(): string | null; + mimeType(value: string | null): this; + + on(type: 'beforesend'): (this: this, xhr: XMLHttpRequest) => void; + on(type: 'progress'): (this: this, progressEvent: ProgressEvent) => void; + on(type: 'error'): (this: this, error: any) => void; + on(type: 'load'): (this: this, data: ResponseData) => void; + on(type: string): (this: this, data: any) => void; + on(type: string, listener: null): this; + on(type: 'beforesend', listener: (this: this, xhr: XMLHttpRequest) => void): this; + on(type: 'progress', listener: (this: this, progressEvent: ProgressEvent) => void): this; + on(type: 'error', listener: (this: this, error: any) => void): this; + on(type: 'load', listener: (this: this, data: ResponseData) => void): this; + on(type: string, listener: (this: this, data: any) => void): this; + + password(): string | null; + password(value: string): this; + + post(): this; + post(data: RequestData): this; + post(callback: (this: this, error: any, d: ResponseData) => void): this; + post(data: RequestData, callback: (this: this, error: any, d: ResponseData) => void): this; + + response(callback: (this: this, response: XMLHttpRequest) => ResponseData): this; + + responseType(): string | null; + responseType(value: string): this; + + send(method: string): this; + send(method: string, data: RequestData): this; + send(method: string, callback: (this: this, error: any | null, d: ResponseData | null) => void): this; + send(method: string, data: RequestData, callback: (this: this, error: any | null, d: ResponseData | null) => void): this; + + timeout(): number; + timeout(value: number): this; + + user(): string | null; + user(value: string): this; +} + +export interface DsvRequest extends Request { + row(value: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow): DsvRequest; +} + +export function csv(url: string): DsvRequest; +export function csv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; +export function csv(url: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; + +export function html(url: string): Request; +export function html(url: string, callback: (this: Request, error: any, d: DocumentFragment) => void): Request; + +export function json(url: string): Request; +export function json(url: string, callback: (this: Request, error: any, d: ParsedObject) => void): Request; + +export function request(url: string): Request; +export function request(url: string, callback: (this: Request, error: any, d: XMLHttpRequest) => void): Request; + +export function text(url: string): Request; +export function text(url: string, callback: (this: Request, error: any, d: string) => void): Request; + +export function tsv(url: string): DsvRequest; +export function tsv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; +export function tsv(url: string, row: (rawRow: DSVRowString, index: number, columns: Array) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray) => void): DsvRequest; + +export function xml(url: string): Request; +export function xml(url: string, callback: (this: Request, error: any, d: any) => void): Request; diff --git a/d3-request/tsconfig.json b/d3-request/tsconfig.json new file mode 100644 index 0000000000..d320e3e9de --- /dev/null +++ b/d3-request/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-request-tests.ts" + ] +}