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.
This commit is contained in:
Tom Wanzek
2016-08-31 22:13:13 -04:00
parent f80ef83201
commit 260dbee9e2
7 changed files with 1029 additions and 55 deletions
+314 -3
View File
@@ -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<d3Dsv.DSVRowString>;
let parseMappedArray: d3Dsv.DSVParsedArray<ParsedTestObject>;
let parseRowsArray: Array<Array<string>>;
let parseRowsMappedArray: Array<ParsedTestObject>;
let columns: Array<string>;
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<string> = 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<string> = 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<string> = 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<string> = 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<string> = 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<string> = 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()
];
}));
+69 -52
View File
@@ -1,65 +1,82 @@
// Type definitions for d3-dsv
// Project: https://www.npmjs.com/package/d3-dsv
// Definitions by: Jason Swearingen <https://jasonswearingen.github.io>
// Type definitions for D3JS d3-dsv module v1.0.1
// Project: https://github.com/d3/d3-dsv/
// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>
// 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<T> extends Array<T> {
columns: Array<string>;
}
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<TRow>(
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<DSVRowString>;
export function csvParse<ParsedRow extends DSVRowAny>(csvString: string, row: (rawRow: DSVRowString, index: number, columns: Array<string>) => ParsedRow): DSVParsedArray<ParsedRow>;
[ ["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<TRow>(
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<Array<string>>;
export function csvParseRows<ParsedRow extends DSVRowAny>(csvString: string, row: (rawRow: Array<string>, index: number) => ParsedRow): Array<ParsedRow>;
// csvFormat(...) ============================================================================
}
export function csvFormat(rows: Array<DSVRowAny>): string;
export function csvFormat(rows: Array<DSVRowAny>, columns: Array<string>): string;
}
// csvFormatRows(...) ========================================================================
export function csvFormatRows(rows: Array<Array<string>>): string;
// ------------------------------------------------------------------------------------------
// TSV Parsers and Formatters
// ------------------------------------------------------------------------------------------
// tsvParse(...) ============================================================================
export function tsvParse(tsvString: string): DSVParsedArray<DSVRowString>;
export function tsvParse<MappedRow extends DSVRowAny>(tsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array<string>) => MappedRow): DSVParsedArray<MappedRow>;
// tsvParseRows(...) ========================================================================
export function tsvParseRows(tsvString: string): Array<Array<string>>;
export function tsvParseRows<MappedRow extends DSVRowAny>(tsvString: string, row: (rawRow: Array<string>, index: number) => MappedRow): Array<MappedRow>;
// tsvFormat(...) ============================================================================
export function tsvFormat(rows: Array<DSVRowAny>): string;
export function tsvFormat(rows: Array<DSVRowAny>, columns: Array<string>): string;
// tsvFormatRows(...) ========================================================================
export function tsvFormatRows(rows: Array<Array<string>>): string;
// ------------------------------------------------------------------------------------------
// DSV Generalized Parsers and Formatters
// ------------------------------------------------------------------------------------------
export interface DSV {
parse(dsvString: string): DSVParsedArray<DSVRowString>;
parse<ParsedRow extends DSVRowAny>(dsvString: string, row: (rawRow: DSVRowString, index: number, columns: Array<string>) => ParsedRow): DSVParsedArray<ParsedRow>;
parseRows(dsvString: string): Array<Array<string>>;
parseRows<ParsedRow extends DSVRowAny>(dsvString: string, row: (rawRow: Array<string>, index: number) => ParsedRow): Array<ParsedRow>;
format(rows: Array<DSVRowAny>): string;
format(rows: Array<DSVRowAny>, columns: Array<string>): string;
formatRows(rows: Array<Array<string>>): string;
}
export function dsvFormat(delimiter: string): DSV;
+8
View File
@@ -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");
+65
View File
@@ -0,0 +1,65 @@
// Type definitions for d3-dsv
// Project: https://www.npmjs.com/package/d3-dsv
// Definitions by: Jason Swearingen <https://jasonswearingen.github.io>
// 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<TRow>(
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<TRow>(
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;
}
}
+470
View File
@@ -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<RequestDatumGET>({ kind: 'Listing' });
// with callback for response handling
let r4: d3Request.Request = d3Request.request(url)
.response(xhr2Listing)
.get<ResponseDatumGET[]>(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<RequestDatumGET, ResponseDatumGET[]>({ 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<ResponseDatumGET[]>('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<ResponseDatumGET[]>('load', function (result: number) { // fails, wrong argument type for callback
// let that: d3Request.Request = this;
// let res: number = result;
// // do something;
// });
listenerResult = r10.on<ResponseDatumGET[]>('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<RequestDatumPOST>({ test: 'NewValue', value: 10 });
// with callback for response handling
let r14: d3Request.Request = d3Request.request(url).response(xhr2Success)
.post<ResponseDatumPOST>(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<RequestDatumPOST, ResponseDatumPOST>({ 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<Array<ResponseDatumGET>>(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<RequestDatumPOST>('POST', { test: 'NewValue', value: 10 });
// method and callback for response handling
let r20: d3Request.Request = d3Request.request(url)
.response(xhr2Listing)
.send<ResponseDatumGET[]>('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<RequestDatumGET, ResponseDatumGET[]>('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<ResponseDatumGET[]>(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<DSVRowString> = data;
console.log(d);
});
// url, row mapping function and callback for response handling
let csvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.csv<ResponseDatumGET>(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<ResponseDatumGET> = 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<DSVRowString> = data;
console.log(d);
});
// url, row mapping function and callback for response handling
let tsvRequestWithRowWithCallback: d3Request.DsvRequest = d3Request.tsv<ResponseDatumGET>(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<ResponseDatumGET> = data;
console.log(data);
});
// -------------------------------------------------------------------------------
// DsvRequest interface
// -------------------------------------------------------------------------------
// row(...) ----------------------------------------------------------------------
csvRequest = csvRequest
.row<ResponseDatumGET>(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();
+84
View File
@@ -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 <https://github.com/Ledragon>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov>, Tom Wanzek <https://github.com/tomwanzek>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import { DSVParsedArray, DSVRowString, DSVRowAny } from 'd3-dsv';
export interface Request {
abort(): this;
get(): this;
get<RequestData>(data: RequestData): this;
get<ResponseData>(callback: (error: any, d: ResponseData) => void): this;
get<RequestData, ResponseData>(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<ResponseData>(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<ResponseData>(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<RequestData>(data: RequestData): this;
post<ResponseData>(callback: (this: this, error: any, d: ResponseData) => void): this;
post<RequestData, ResponseData>(data: RequestData, callback: (this: this, error: any, d: ResponseData) => void): this;
response<ResponseData>(callback: (this: this, response: XMLHttpRequest) => ResponseData): this;
responseType(): string | null;
responseType(value: string): this;
send(method: string): this;
send<RequestData>(method: string, data: RequestData): this;
send<ResponseData>(method: string, callback: (this: this, error: any | null, d: ResponseData | null) => void): this;
send<RequestData, ResponseData>(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<ParsedRow extends DSVRowAny>(value: (rawRow: DSVRowString, index: number, columns: Array<string>) => ParsedRow): DsvRequest;
}
export function csv(url: string): DsvRequest;
export function csv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray<DSVRowString>) => void): DsvRequest;
export function csv<ParsedRow extends DSVRowAny>(url: string, row: (rawRow: DSVRowString, index: number, columns: Array<string>) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray<ParsedRow>) => 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<ParsedObject extends { [key: string]: any }>(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<DSVRowString>) => void): DsvRequest;
export function tsv<ParsedRow extends DSVRowAny>(url: string, row: (rawRow: DSVRowString, index: number, columns: Array<string>) => ParsedRow, callback: (this: DsvRequest, error: any, d: DSVParsedArray<ParsedRow>) => void): DsvRequest;
export function xml(url: string): Request;
export function xml(url: string, callback: (this: Request, error: any, d: any) => void): Request;
+19
View File
@@ -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"
]
}