Skip to content

Commit

Permalink
fix(types): rename toString to asString as it conflicts with default …
Browse files Browse the repository at this point in the history
…build-in objects
  • Loading branch information
woutervanbakel committed Mar 18, 2021
1 parent 704551e commit 2146e0c
Show file tree
Hide file tree
Showing 16 changed files with 54 additions and 53 deletions.
4 changes: 2 additions & 2 deletions src/express/ErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Exception, isError, isException, isResults, isText, Result, Results, toResult, toString } from '../types';
import { asString, Exception, isError, isException, isResults, isText, Result, Results, toResult } from '../types';
import express from 'express';
import { HttpStatus, isResponse, OriginatedError, Response, rest, toHttpStatus, toOriginatedError } from '../http';
import { choose } from '../utils';
Expand Down Expand Up @@ -45,7 +45,7 @@ const toBody = ({ origin, options }: OriginatedError): Response => {
.case(
// This service fails with a string
o => isText(o),
(o: Response) => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(toString(o))])
(o: Response) => toResponse(options?.onError ?? HttpStatus.BadRequest, [toResult(asString(o))])
)
.else(() => toResponse(HttpStatus.InternalServerError, [toResult('Unknown error')]));
};
Expand Down
4 changes: 2 additions & 2 deletions src/http/ContentType.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Enum, Get, ofGet, toString } from '../types';
import { asString, Enum, Get, ofGet } from '../types';
import formUrlEncoded from 'form-urlencoded';

export class ContentType extends Enum {
Expand All @@ -8,7 +8,7 @@ export class ContentType extends Enum {
static Text = new ContentType('text', 'text/plain');
static Xml = new ContentType('xml', 'application/xml');

private constructor(name: string, readonly type: string, protected readonly encoder: Get<string> = b => toString(b)) {
private constructor(name: string, readonly type: string, protected readonly encoder: Get<string> = b => asString(b)) {
super(name, type);
}

Expand Down
4 changes: 2 additions & 2 deletions src/mongo/MongoProvider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ctx, Id, isDefined, Json, JsonValue, List, toList, toString } from '../types';
import { asString, ctx, Id, isDefined, Json, JsonValue, List, toList } from '../types';
import { Collection, FilterQuery, MongoClient } from 'mongodb';
import { when } from '../validation';

Expand Down Expand Up @@ -41,7 +41,7 @@ export class MongoProvider {
}

by(key: string, value: JsonValue): Promise<List<Json>> {
return this.find({ [key]: toString(value) });
return this.find({ [key]: asString(value) });
}

group(qs: FilterQuery<any>[]): Promise<Json[]> {
Expand Down
6 changes: 3 additions & 3 deletions src/sql/TableGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import { reject } from '../utils';
import { Table } from './Table';

export class TableGateway<T extends Table> implements Gateway {
constructor(readonly table: T, readonly provider: DataProvider = table.db.provider) {
}
constructor(readonly table: T, readonly provider: DataProvider = table.db.provider) {}

all(): Promise<List<Json>> {
return this.provider.query(this.table.select());
}

byId(id: Id): Promise<Json | undefined> {
return this.provider.query(this.table.select().where(this.table.id.is(id)))
return this.provider
.query(this.table.select().where(this.table.id.is(id)))
.then(js => js.first())
.then(j => this.table.in(j));
}
Expand Down
4 changes: 2 additions & 2 deletions src/types/Exception.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { text, Text, toString } from './Text';
import { asString, Text, text } from './Text';
import { Enum } from './Enum';
import { isDefined } from './Is';

Expand All @@ -17,4 +17,4 @@ export class Exception extends Enum {
because = (reason: Text): Exception => new Exception(this.message, reason);
}

export const isException = (e?: unknown, t?: Text): e is Exception => e instanceof Exception && (isDefined(t) ? e.equals(toString(t)) : true);
export const isException = (e?: unknown, t?: Text): e is Exception => e instanceof Exception && (isDefined(t) ? e.equals(asString(t)) : true);
6 changes: 5 additions & 1 deletion src/types/List.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ export class List<T> extends Array<T> {

last = (p?: (value: T, index: number, array: T[]) => unknown, params?: unknown): T => (p ? this.filter(p, params).last() : this[this.length - 1]);

toJSON = (): Json[] => this.reduce((a, i) => { a.push(json.parse(i)); return a; }, new Array<Json>());
toJSON = (): Json[] =>
this.reduce((a, i) => {
a.push(json.parse(i));
return a;
}, new Array<Json>());

map = <U>(f: (value: T, index: number, array: T[]) => U, params?: unknown): List<U> => super.map(f, params) as List<U>;

Expand Down
10 changes: 5 additions & 5 deletions src/types/Text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ export type Text = { toString(): string };

export const isText = (t?: unknown): t is Text => isDefined(t) && isFunc<string, any>((t as any).toString);

export const toString = (t?: unknown, alt: Get<Text> = ''): string => (isText(t) ? t : ofGet(alt)).toString();
export const asString = (t?: unknown, alt: Get<Text> = ''): string => (isText(t) ? t : ofGet(alt)).toString();

// eslint-disable-next-line security/detect-non-literal-regexp
export const replaceAll = (t: Text, search: Text, replace: Text = ''): string => toString(t).replace(new RegExp(toString(search), 'g'), toString(replace));
export const replaceAll = (t: Text, search: Text, replace: Text = ''): string => asString(t).replace(new RegExp(asString(search), 'g'), asString(replace));

class ToText implements Text {
constructor(readonly subject: string) {}
Expand Down Expand Up @@ -65,9 +65,9 @@ class ToText implements Text {

isLike = (other?: unknown): boolean => this.trim.lower.toString() === text(other).trim.lower.toString();

endsWith = (end?: unknown): boolean => this.subject.endsWith(toString(end));
endsWith = (end?: unknown): boolean => this.subject.endsWith(asString(end));

startsWith = (end?: unknown): boolean => this.subject.startsWith(toString(end));
startsWith = (end?: unknown): boolean => this.subject.startsWith(asString(end));

map = (func: Get<string, string>): ToText => text(ofGet(func, this.subject));

Expand All @@ -79,6 +79,6 @@ class ToText implements Text {
}

export const text = (subject?: unknown, alt = ''): ToText => {
const sub = toString(subject) ?? alt;
const sub = asString(subject) ?? alt;
return new ToText(sub !== '[object Object]' ? sub : '');
};
4 changes: 2 additions & 2 deletions src/utils/Parser.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { meta, text, Text, toName, toString } from '../types';
import { asString, meta, Text, text, toName } from '../types';

export type ParseOptions = { property?: unknown; actual?: unknown };

const props = (subject: unknown = {}, template: Text = ''): string =>
meta(subject)
.entries()
.reduce((res, [k, v]) => res.replace(`{this.${k}}`, toString(v)), toString(template));
.reduce((res, [k, v]) => res.replace(`{this.${k}}`, asString(v)), asString(template));

export const toText = (subject: unknown, template: Text, options: ParseOptions = {}): Text =>
text(template)
Expand Down
4 changes: 2 additions & 2 deletions test/data/CollectionGateway.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CollectionGateway, Exception, resolve, Json, toJson, toList } from '../../src';
import { CollectionGateway, Exception, Json, resolve, toJson, toList } from '../../src';
import { Dev } from '../ref';
import '@thisisagile/easy-test';

Expand Down Expand Up @@ -38,7 +38,7 @@ describe('CollectionGateway', () => {

test('all returns all devs', async () => {
const a = await gateway.all();
expect([...a]).toStrictEqual([...Dev.All.toJSON()]);
expect(a.toJSON()).toStrictEqual(Dev.All.toJSON());
});

test('all returns a copy of all devs', async () => {
Expand Down
10 changes: 8 additions & 2 deletions test/domain/Repo.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Dev, DevRepo, DevRoutedGateway, DevUri } from '../ref';
import { fits, mock } from '@thisisagile/easy-test';
import { Exception, list, toResults } from '../../src';
import { Exception, Json, list, toList, toResults } from '../../src';
import '@thisisagile/easy-test';
import { Json } from '@thisisagile/easy-test/dist/utils/Types';

describe('Repo', () => {
const devs = list<Json>(Dev.Sander.toJSON(), Dev.Jeroen.toJSON(), Dev.Naoufal.toJSON());
Expand Down Expand Up @@ -35,6 +34,13 @@ describe('Repo', () => {
expect(gateway.byId).toHaveBeenCalledWith(42);
});

test('by triggers the gateway', async () => {
gateway.by = mock.resolve(toList(Dev.Naoufal));
const res = await repo.by('level', '42');
expect(res.toJSON()).toMatchObject(toList(Dev.Naoufal).toJSON());
expect(gateway.by).toHaveBeenCalledWith('level', '42');
});

test('search triggers gateway', async () => {
gateway.search = mock.resolve(devs);
const ds = await repo.search('Kim');
Expand Down
6 changes: 2 additions & 4 deletions test/express/RequestContextHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ import { mock } from '@thisisagile/easy-test';
import { ctx, requestContext } from '../../src';

describe('requestContext', () => {
test('Correlation already in request', () => {
const m = jest.spyOn(ctx.request, 'create');
test('correlation already in request', () => {
const m = jest.spyOn(ctx.request, 'create').mockImplementationOnce((fn: NextFunction) => fn());
const next = mock.return();

m.mockImplementationOnce((fn: NextFunction) => fn());
requestContext({} as Request, {} as Response, next);

expect(m).toHaveBeenCalled();
expect(next).toHaveBeenCalled();
});
Expand Down
6 changes: 3 additions & 3 deletions test/sql/TableGateway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ expect.extend({
.undefined(q => q, 'Query is unknown.')
.not(
q => q.toString() === expected.toString(),
q => `Expected Query to be '${expected}', but got '${q}' instead`,
q => `Expected Query to be '${expected}', but got '${q}' instead`
)
.else(`Query ${actual} does not match '${expected}'.`);
},
Expand All @@ -34,8 +34,8 @@ describe('TableGateway', () => {

test('byId', async () => {
const id = 11;
provider.query = mock.resolve(toList({Id: 6, Name: "Pawel", CodingLevel: "3", Language: "python"}));
await expect(target.byId(id)).resolves.toStrictEqual(expect.objectContaining({id: 6, name: "Pawel", level: 3, language: "python"}));
provider.query = mock.resolve(toList({ Id: 6, Name: 'Pawel', CodingLevel: '3', Language: 'python' }));
await expect(target.byId(id)).resolves.toStrictEqual(expect.objectContaining({ id: 6, name: 'Pawel', level: 3, language: 'python' }));
expect(provider.query).toHaveBeenQueriedWith(table.select().where(table.id.is(id)));
});
});
18 changes: 9 additions & 9 deletions test/types/Text.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isText, replaceAll, toString } from '../../src';
import { asString, isText, replaceAll } from '../../src';
import { Dev } from '../ref';

describe('isText', () => {
Expand All @@ -15,17 +15,17 @@ describe('isText', () => {
});

test('ifText without alt', () => {
expect(toString()).toBe('');
expect(toString('hallo')).toBe('hallo');
expect(toString(Dev.Jeroen)).toBe('Jeroen');
expect(asString()).toBe('');
expect(asString('hallo')).toBe('hallo');
expect(asString(Dev.Jeroen)).toBe('Jeroen');
});

test('ifText with alt', () => {
expect(toString(undefined, 'alt')).toBe('alt');
expect(toString(undefined, () => 'alt')).toBe('alt');
expect(toString(has, () => 'alt')).toBe('alt');
expect(toString('hallo', 'alt')).toBe('hallo');
expect(toString(Dev.Jeroen, Dev.Naoufal)).toBe('Jeroen');
expect(asString(undefined, 'alt')).toBe('alt');
expect(asString(undefined, () => 'alt')).toBe('alt');
expect(asString(has, () => 'alt')).toBe('alt');
expect(asString('hallo', 'alt')).toBe('hallo');
expect(asString(Dev.Jeroen, Dev.Naoufal)).toBe('Jeroen');
});

test('replaceAll', () => {
Expand Down
3 changes: 1 addition & 2 deletions test/types/Validatable.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Dev } from '../ref';
import { isValidatable } from '../../src';
import { Validatable } from '@thisisagile/easy-test/dist/utils/Types';
import { isValidatable, Validatable } from '../../src';
import { mock } from '@thisisagile/easy-test';

class ValidateMe implements Validatable {
Expand Down
12 changes: 4 additions & 8 deletions test/utils/Map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,19 @@ describe('Map', () => {
});

test('empty map.from with undefined is undefined', () => {
const j = empty.in();
expect(j).toMatchObject({});
expect(empty.in()).toMatchObject({});
});

test('empty map.to with undefined is undefined', () => {
const j = empty.out();
expect(j).toMatchObject({});
expect(empty.out()).toMatchObject({});
});

test('empty map.from is correct', () => {
const j = empty.in(devData.jeroen);
expect(j).toMatchObject(devData.jeroen);
expect(empty.in(devData.jeroen)).toMatchObject(devData.jeroen);
});

test('empty map.to is correct', () => {
const j = empty.out(devData.jeroen);
expect(j).toMatchObject(devData.jeroen);
expect(empty.out(devData.jeroen)).toMatchObject(devData.jeroen);
});

test('map.to is correct', () => {
Expand Down
6 changes: 2 additions & 4 deletions test/validation/Constraints.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,12 @@ describe('Constraints', () => {
language: 'java',
title: 'Prof.',
});
const r = validate(t);
expect(r).toBeValid();
expect(validate(t)).toBeValid();
});

test('All constraints fail.', () => {
const t = new Tester({ one: 42, two: 0 });
const r = validate(t);
expect(r).not.toBeValid();
expect(validate(t)).not.toBeValid();
});
});

Expand Down

0 comments on commit 2146e0c

Please sign in to comment.