New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@thisisagile/easy

Package Overview
Dependencies
Maintainers
2
Versions
1277
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@thisisagile/easy - npm Package Compare versions

Comparing version 1.14.4 to 1.14.5

dist/validation/Match.d.ts

2

dist/data/index.d.ts

@@ -1,1 +0,1 @@

export * from "./Query";
export * from './Query';

@@ -1,2 +0,2 @@

import { Json, JsonValue } from "../types";
import { Json, JsonValue } from '../types';
export declare class Query {

@@ -3,0 +3,0 @@ readonly key: string;

@@ -1,3 +0,3 @@

export * from "./Entity";
export * from "./Record";
export * from "./Repo";
export * from './Entity';
export * from './Record';
export * from './Repo';

@@ -11,3 +11,5 @@ "use strict";

}
get isValid() { return validation_1.validate(this).isValid; }
get isValid() {
return validation_1.validate(this).isValid;
}
toJSON() {

@@ -14,0 +16,0 @@ return types_1.jsonify({ ...this, state: undefined });

@@ -15,9 +15,11 @@ "use strict";

this.exists = (id) => this.gateway.exists(id);
this.add = (json) => validation_1.when(new this.ctor(json)).not.isValid.reject()
this.add = (json) => validation_1.when(new this.ctor(json))
.not.isValid.reject()
.then(i => this.validate(i))
.then(i => this.gateway.add(types_1.jsonify(i)))
.then(j => new this.ctor(j));
this.update = (json) => this.gateway.byId(json.id)
this.update = (json) => this.gateway
.byId(json.id)
.then(j => validation_1.when(j).not.isDefined.reject('Does not exist'))
.then(j => (new this.ctor(j)).update(j))
.then(j => new this.ctor(j).update(j))
.then(i => validation_1.when(i).not.isValid.reject())

@@ -24,0 +26,0 @@ .then(i => this.gateway.update(i.toJSON()))

@@ -1,2 +0,1 @@

/// <reference types="node" />
import { Express, RequestHandler } from 'express';

@@ -8,5 +7,5 @@ import { AppProvider } from '../services';

constructor(app?: Express);
listen: (port: number, message?: string) => import("http").Server;
listen: (port: number, message?: string) => void;
use: (h: RequestHandler) => void;
route: (resource: Constructor) => void;
}

@@ -9,7 +9,13 @@ "use strict";

const services_1 = require("../services");
const handle = (endpoint) => (req, res, next) => endpoint(services_1.toReq(req)).then((r) => res.status(200).json(services_1.toRestResult(r))).catch(next);
const handle = (endpoint) => (req, res, next) => endpoint(services_1.toReq(req))
.then((r) => res.status(200).json(services_1.toRestResult(r)))
.catch(next);
class ExpressProvider {
constructor(app = express_1.default()) {
this.app = app;
this.listen = (port, message = `Service is listening on port ${port}.`) => this.app.listen(port, () => { console.log(message); });
this.listen = (port, message = `Service is listening on port ${port}.`) => {
this.app.listen(port, () => {
console.log(message);
});
};
this.use = (h) => {

@@ -16,0 +22,0 @@ this.app.use(h);

@@ -1,1 +0,1 @@

export * from "./ExpressProvider";
export * from './ExpressProvider';

@@ -1,8 +0,8 @@

export * from "./data";
export * from "./domain";
export * from "./express";
export * from "./process";
export * from "./services";
export * from "./types";
export * from "./utils";
export * from "./validation";
export * from './data';
export * from './domain';
export * from './express';
export * from './process';
export * from './services';
export * from './types';
export * from './utils';
export * from './validation';

@@ -1,2 +0,2 @@

export * from "./Manage";
export * from "./Select";
export * from './Manage';
export * from './Select';

@@ -18,7 +18,8 @@ "use strict";

constructor() {
this.execute = ({ uri, verb, body, transform = (r) => r, options = RequestOptions_1.RequestOptions.Json }) => axios_1.default.request({
this.execute = ({ uri, verb, body, transform = (r) => r, options = RequestOptions_1.RequestOptions.Json }) => axios_1.default
.request({
url: uri.toString(),
method: verb.toString(),
headers: options.headers,
data: body
data: body,
})

@@ -25,0 +26,0 @@ .then(r => transform(r))

@@ -5,3 +5,5 @@ "use strict";

const types_1 = require("../types");
const formEncode = (body) => Object.entries(body).map(([key, value]) => `${key}=${value}`).join("&");
const formEncode = (body) => Object.entries(body)
.map(([key, value]) => `${key}=${value}`)
.join('&');
const jsonEncode = (body) => JSON.stringify(body);

@@ -13,10 +15,10 @@ class ContentType extends types_1.Enum {

this.encoder = encoder;
this.encode = (body) => types_1.isDefined(body) ? types_1.ofGet(this.encoder, body) : undefined;
this.encode = (body) => (types_1.isDefined(body) ? types_1.ofGet(this.encoder, body) : undefined);
}
}
exports.ContentType = ContentType;
ContentType.Json = new ContentType("json", "application/json", b => jsonEncode(b));
ContentType.Text = new ContentType("text", "text/plain", b => b.toString());
ContentType.Xml = new ContentType("xml", "application/xml");
ContentType.Form = new ContentType("form", "application/x-www-form-urlencoded", b => formEncode(b));
ContentType.Json = new ContentType('json', 'application/json', b => jsonEncode(b));
ContentType.Text = new ContentType('text', 'text/plain', b => b.toString());
ContentType.Xml = new ContentType('xml', 'application/xml');
ContentType.Form = new ContentType('form', 'application/x-www-form-urlencoded', b => formEncode(b));
//# sourceMappingURL=ContentType.js.map

@@ -9,16 +9,18 @@ "use strict";

}
get status() { return this.id; }
get status() {
return this.id;
}
}
exports.HttpStatus = HttpStatus;
HttpStatus.Ok = new HttpStatus("Ok", 200);
HttpStatus.Created = new HttpStatus("Created", 201);
HttpStatus.NoContent = new HttpStatus("No content", 204);
HttpStatus.BadRequest = new HttpStatus("Bad request", 400);
HttpStatus.NotAuthorized = new HttpStatus("Not authorized", 401);
HttpStatus.Forbidden = new HttpStatus("Forbidden", 403);
HttpStatus.NotFound = new HttpStatus("Not found", 404);
HttpStatus.Conflict = new HttpStatus("Conflict", 409);
HttpStatus.InternalServerError = new HttpStatus("Internal server error", 500);
HttpStatus.NotImplemented = new HttpStatus("Not implemented", 501);
HttpStatus.BadGateway = new HttpStatus("Bad gateway", 502);
HttpStatus.Ok = new HttpStatus('Ok', 200);
HttpStatus.Created = new HttpStatus('Created', 201);
HttpStatus.NoContent = new HttpStatus('No content', 204);
HttpStatus.BadRequest = new HttpStatus('Bad request', 400);
HttpStatus.NotAuthorized = new HttpStatus('Not authorized', 401);
HttpStatus.Forbidden = new HttpStatus('Forbidden', 403);
HttpStatus.NotFound = new HttpStatus('Not found', 404);
HttpStatus.Conflict = new HttpStatus('Conflict', 409);
HttpStatus.InternalServerError = new HttpStatus('Internal server error', 500);
HttpStatus.NotImplemented = new HttpStatus('Not implemented', 501);
HttpStatus.BadGateway = new HttpStatus('Bad gateway', 502);
//# sourceMappingURL=HttpStatus.js.map

@@ -6,3 +6,5 @@ "use strict";

class HttpVerb extends types_1.Enum {
constructor(name) { super(name, name.toLowerCase(), name.toUpperCase()); }
constructor(name) {
super(name, name.toLowerCase(), name.toUpperCase());
}
}

@@ -9,0 +11,0 @@ exports.HttpVerb = HttpVerb;

@@ -1,15 +0,13 @@

export * from "./Api";
export * from "./AppProvider";
export * from "./AxiosProvider";
export * from "./ContentType";
export * from "./EasyResponse";
export * from "../express/ExpressProvider";
export * from "./HttpStatus";
export * from "./HttpVerb";
export * from "./Req";
export * from "./RequestOptions";
export * from "./RequestProvider";
export * from "./RestResult";
export * from "./Route";
export * from "./RouteGateway";
export * from "./Verb";
export * from './Api';
export * from './AppProvider';
export * from './AxiosProvider';
export * from './ContentType';
export * from './HttpStatus';
export * from './HttpVerb';
export * from './Req';
export * from './RequestOptions';
export * from './RequestProvider';
export * from './RestResult';
export * from './Route';
export * from './RouteGateway';
export * from './Verb';

@@ -17,4 +17,2 @@ "use strict";

__exportStar(require("./ContentType"), exports);
__exportStar(require("./EasyResponse"), exports);
__exportStar(require("../express/ExpressProvider"), exports);
__exportStar(require("./HttpStatus"), exports);

@@ -21,0 +19,0 @@ __exportStar(require("./HttpVerb"), exports);

@@ -9,2 +9,10 @@ import { Id, Json, JsonValue } from '../types';

};
export declare const toReq: (req: any) => Req;
export declare const toReq: (req: {
params?: {
id?: unknown;
};
query?: {
q?: unknown;
};
body?: unknown;
}) => Req;

@@ -11,3 +11,3 @@ "use strict";

q: (_b = req.query) === null || _b === void 0 ? void 0 : _b.q,
body: req.body
body: req.body,
});

@@ -14,0 +14,0 @@ };

@@ -12,3 +12,3 @@ "use strict";

itemCount: items.length,
}
},
});

@@ -23,3 +23,3 @@ const error = (errors) => {

errorCount: errors.length,
}
},
});

@@ -26,0 +26,0 @@ };

@@ -6,3 +6,3 @@ import { Constructor, List, Uri } from '../types';

export declare type Endpoint<T = unknown> = (re: Req) => Promise<T | List<T>>;
declare class Routes<T> {
declare class Routes {
readonly resource: unknown;

@@ -16,3 +16,3 @@ constructor(resource: unknown);

}
export declare const routes: <T>(resource: Constructor<T>) => Routes<T>;
export declare const routes: (resource: Constructor) => Routes;
export {};

@@ -5,3 +5,5 @@ "use strict";

const types_1 = require("../types");
const route = (uri) => (subject) => { types_1.meta(subject).set('route', uri); };
const route = (uri) => (subject) => {
types_1.meta(subject).set('route', uri);
};
exports.route = route;

@@ -12,5 +14,8 @@ class Routes {

}
get route() { return types_1.meta(this.resource).get('route'); }
get route() {
return types_1.meta(this.resource).get('route');
}
get endpoints() {
return types_1.meta(this.resource).properties('verb')
return types_1.meta(this.resource)
.properties('verb')
.map(p => ({ verb: p.get('verb').verb, endpoint: this.resource[p.property] }));

@@ -17,0 +22,0 @@ }

import { Api } from './Api';
import { Gateway, Id, Json, JsonValue, Uri } from '../types';
import { List } from '../types/List';
import { Gateway, Id, Json, JsonValue, List, Uri } from '../types';
export declare class RouteGateway implements Gateway {

@@ -5,0 +4,0 @@ readonly api: Api;

@@ -7,3 +7,5 @@ "use strict";

const types_1 = require("../types");
const verb = (v) => (subject, property) => { types_1.meta(subject).property(property).set('verb', v); };
const verb = (v) => (subject, property) => {
types_1.meta(subject).property(property).set('verb', v);
};
const get = (onOk = HttpStatus_1.HttpStatus.Ok, onError = HttpStatus_1.HttpStatus.NotFound) => verb({ verb: HttpVerb_1.HttpVerb.Get, onOk, onError });

@@ -10,0 +12,0 @@ exports.get = get;

@@ -5,4 +5,4 @@ "use strict";

const Is_1 = require("./Is");
const toArray = (...items) => (items.length > 1) ? items : Is_1.isArray(items[0]) ? items[0] : Is_1.isDefined(items[0]) ? [items[0]] : [];
const toArray = (...items) => items.length > 1 ? items : Is_1.isArray(items[0]) ? items[0] : Is_1.isDefined(items[0]) ? [items[0]] : [];
exports.toArray = toArray;
//# sourceMappingURL=Array.js.map

@@ -5,6 +5,6 @@ "use strict";

const Is_1 = require("./Is");
const ofGet = (g, ...params) => Is_1.isFunction(g) ? g(...params) : g;
const ofGet = (g, ...params) => (Is_1.isFunction(g) ? g(...params) : g);
exports.ofGet = ofGet;
const ofProperty = (t, p) => Is_1.isFunction(p) ? p(t) : t[p];
const ofProperty = (t, p) => (Is_1.isFunction(p) ? p(t) : t[p]);
exports.ofProperty = ofProperty;
//# sourceMappingURL=Constructor.js.map

@@ -15,14 +15,22 @@ "use strict";

static all() {
return Meta_1.meta(this).values().filter((e) => exports.isEnum(e));
return Meta_1.meta(this)
.values()
.filter((e) => exports.isEnum(e));
}
static byId(id, alt) {
var _a;
return (_a = Meta_1.meta(this).values().first((e) => exports.isEnum(e) && e.id === id)) !== null && _a !== void 0 ? _a : Constructor_1.ofGet(alt);
return ((_a = Meta_1.meta(this)
.values()
.first((e) => exports.isEnum(e) && e.id === id)) !== null && _a !== void 0 ? _a : Constructor_1.ofGet(alt));
}
get isValid() { return Is_1.isDefined(this.id); }
toString() { return this.id.toString(); }
get isValid() {
return Is_1.isDefined(this.id);
}
toString() {
return this.id.toString();
}
}
exports.Enum = Enum;
const isEnum = (e) => Is_1.isDefined(e) && (e instanceof Enum) && IsA_1.isAn(e, 'name', 'id', 'code');
const isEnum = (e) => Is_1.isDefined(e) && e instanceof Enum && IsA_1.isAn(e, 'name', 'id', 'code');
exports.isEnum = isEnum;
//# sourceMappingURL=Enum.js.map

@@ -1,20 +0,20 @@

export * from "./Array";
export * from "./Constructor";
export * from "./Enum";
export * from "./Gateway";
export * from "./Id";
export * from "./Is";
export * from "./IsA";
export * from "./IsDate";
export * from "./Json";
export * from "./List";
export * from "./Message";
export * from "./Meta";
export * from "./Result";
export * from "./Results";
export * from "./Text";
export * from "./Uri";
export * from "./Validatable";
export * from './Array';
export * from './Constructor';
export * from './Enum';
export * from './Gateway';
export * from './Id';
export * from './Is';
export * from './IsA';
export * from './IsDate';
export * from './Json';
export * from './List';
export * from './Message';
export * from './Meta';
export * from './Result';
export * from './Results';
export * from './Text';
export * from './Uri';
export * from './Validatable';
export { inFuture } from './IsDate';
export { inPast } from './IsDate';
export { isDate } from './IsDate';

@@ -6,3 +6,3 @@ import { Constructor } from './Constructor';

export declare const isString: (o?: unknown) => o is string;
export declare const isObject: (o?: unknown) => o is Object;
export declare const isObject: (o?: unknown) => boolean;
export declare const isEmptyObject: (o?: unknown) => boolean;

@@ -9,0 +9,0 @@ export declare const isFunction: (o?: unknown) => o is (...params: unknown[]) => unknown;

@@ -24,4 +24,4 @@ "use strict";

exports.isIn = isIn;
const isPrimitive = (o) => (o !== null) && !exports.isObject(o) && !exports.isFunction(o) && !exports.isArray(o);
const isPrimitive = (o) => o !== null && !exports.isObject(o) && !exports.isFunction(o) && !exports.isArray(o);
exports.isPrimitive = isPrimitive;
//# sourceMappingURL=Is.js.map

@@ -8,4 +8,4 @@ "use strict";

exports.isAn = exports.isA;
const isError = (e) => exports.isAn(e, "name", "message");
const isError = (e) => exports.isAn(e, 'name', 'message');
exports.isError = isError;
//# sourceMappingURL=IsA.js.map

@@ -13,3 +13,3 @@ "use strict";

yesterday: () => exports.days.add(exports.days.today(), -1),
tomorrow: () => exports.days.add(exports.days.today(), 1)
tomorrow: () => exports.days.add(exports.days.today(), 1),
};

@@ -16,0 +16,0 @@ const inPast = (o) => exports.isDate(o) && o <= exports.days.today();

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonify = void 0;
const jsonify = (subject = {}, additional) => ({ ...(JSON.parse(JSON.stringify(subject))), ...additional });
const jsonify = (subject = {}, additional) => ({ ...JSON.parse(JSON.stringify(subject)), ...additional });
exports.jsonify = jsonify;
//# sourceMappingURL=Json.js.map

@@ -6,8 +6,8 @@ import { GetProperty } from './Constructor';

desc: (p: GetProperty<T, any>) => List<T>;
first: (p?: (value: T, index: number, array: T[]) => unknown, params?: any) => T;
last: (p?: (value: T, index: number, array: T[]) => unknown, params?: any) => T;
first: (p?: (value: T, index: number, array: T[]) => unknown, params?: unknown) => T;
last: (p?: (value: T, index: number, array: T[]) => unknown, params?: unknown) => T;
toJSON: () => List<Json>;
map: <U>(f: (value: T, index: number, array: T[]) => U, params?: any) => List<U>;
mapDefined: <U>(f: (value: T, index: number, array: T[]) => U, params?: any) => List<U>;
filter: (p: (value: T, index: number, array: T[]) => unknown, params?: any) => List<T>;
map: <U>(f: (value: T, index: number, array: T[]) => U, params?: unknown) => List<U>;
mapDefined: <U>(f: (value: T, index: number, array: T[]) => U, params?: unknown) => List<U>;
filter: (p: (value: T, index: number, array: T[]) => unknown, params?: unknown) => List<T>;
concat: (...items: (T | ConcatArray<T>)[]) => List<T>;

@@ -14,0 +14,0 @@ add: (...items: (T | T[])[]) => this;

@@ -14,4 +14,4 @@ "use strict";

this.desc = (p) => this.sort((e1, e2) => (Constructor_1.ofProperty(e1, p) < Constructor_1.ofProperty(e2, p) ? 1 : -1));
this.first = (p, params) => p ? this.filter(p, params).first() : this[0];
this.last = (p, params) => p ? this.filter(p, params).last() : this[this.length - 1];
this.first = (p, params) => (p ? this.filter(p, params).first() : this[0]);
this.last = (p, params) => (p ? this.filter(p, params).last() : this[this.length - 1]);
this.toJSON = () => this.map(i => Json_1.jsonify(i));

@@ -31,3 +31,3 @@ this.map = (f, params) => super.map(f, params);

exports.list = list;
const toList = (...items) => (items.length > 1) ? exports.list(...items) : exports.list(items[0]);
const toList = (...items) => (items.length > 1 ? exports.list(...items) : exports.list(items[0]));
exports.toList = toList;

@@ -34,0 +34,0 @@ const isList = (l) => Is_1.isDefined(l) && Is_1.isArray(l) && IsA_1.isA(l, 'first', 'last', 'asc', 'desc');

@@ -20,4 +20,6 @@ "use strict";

.map(p => this.property(p))
.filter(p => key ? p.get(key) : p);
this.keys = (key) => this.properties().map(p => p.get(key)).filter(v => Is_1.isDefined(v));
.filter(p => (key ? p.get(key) : p));
this.keys = (key) => this.properties()
.map(p => p.get(key))
.filter(v => Is_1.isDefined(v));
this.values = () => this.properties().map(p => p.value);

@@ -32,3 +34,3 @@ this.property = (property) => new PropertyMeta(this.subject, property);

this.data = data;
this.get = (key) => Is_1.isDefined(this.data) && Is_1.isDefined(this.data[key]) ? this.data[key] : undefined;
this.get = (key) => (Is_1.isDefined(this.data) && Is_1.isDefined(this.data[key]) ? this.data[key] : undefined);
this.set = (key, value) => {

@@ -39,3 +41,5 @@ Reflect.defineMetadata(this.property, { ...this.data, [key]: value }, this.subject);

}
get value() { return this.subject[this.property]; }
get value() {
return this.subject[this.property];
}
}

@@ -42,0 +46,0 @@ const meta = (subject) => new ClassMeta(subject !== null && subject !== void 0 ? subject : {});

@@ -7,7 +7,3 @@ import { Text } from './Text';

};
export declare const result: (message: Text, domain?: string, location?: string) => {
message: Text;
domain: string;
location: string;
};
export declare const result: (message: Text, domain?: string, location?: string) => Result;
export declare const isResult: (r?: unknown) => r is Result;

@@ -5,6 +5,6 @@ "use strict";

const IsA_1 = require("./IsA");
const result = (message, domain = "easy", location) => ({ message, domain, location });
const result = (message, domain = 'easy', location) => ({ message, domain, location });
exports.result = result;
const isResult = (r) => IsA_1.isA(r, "message");
const isResult = (r) => IsA_1.isA(r, 'message');
exports.isResult = isResult;
//# sourceMappingURL=Result.js.map

@@ -6,3 +6,3 @@ "use strict";

const Is_1 = require("./Is");
const parse = (...rs) => rs.map(r => Result_1.isResult(r) ? r : Result_1.result(r.toString(), 'easy'));
const parse = (...rs) => rs.map(r => (Result_1.isResult(r) ? r : Result_1.result(r.toString(), 'easy')));
class Results {

@@ -13,4 +13,8 @@ constructor(...rs) {

}
get length() { return this.results.length; }
get isValid() { return this.results.length === 0; }
get length() {
return this.results.length;
}
get isValid() {
return this.results.length === 0;
}
}

@@ -17,0 +21,0 @@ exports.Results = Results;

@@ -5,4 +5,4 @@ "use strict";

const IsA_1 = require("./IsA");
const isText = (t) => IsA_1.isA(t, "toString");
const isText = (t) => IsA_1.isA(t, 'toString');
exports.isText = isText;
//# sourceMappingURL=Text.js.map

@@ -12,5 +12,7 @@ "use strict";

path: (key) => ({ key, segment: `:${key}` }),
query: (key) => ({ key, query: (value) => value ? `${key}=${value}` : undefined }),
query: (key) => ({ key, query: (value) => (value ? `${key}=${value}` : undefined) }),
};
const toRoute = (...segments) => List_1.list(...segments).mapDefined(s => s.segment).join('/');
const toRoute = (...segments) => List_1.list(...segments)
.mapDefined(s => s.segment)
.join('/');
const parse = (route, p) => route.replace(p.segment.segment, p.value.toString());

@@ -30,9 +32,15 @@ class Uri {

}
get route() { return toRoute(exports.uri.segment(''), ...this.segments); }
get path() { return toRoute(exports.uri.segment(''), this.resource, ...this.segments); }
get complete() { return toRoute(this.host, this.resource, ...this.segments); }
get route() {
return toRoute(exports.uri.segment(''), ...this.segments);
}
get path() {
return toRoute(exports.uri.segment(''), this.resource, ...this.segments);
}
get complete() {
return toRoute(this.host, this.resource, ...this.segments);
}
toString() {
var _a;
const route = this.props.reduce((r, p) => parse(r, p), this.complete);
const q = (_a = this.props.mapDefined(p => { var _a, _b; return ((_a = p.segment) === null || _a === void 0 ? void 0 : _a.query) ? (_b = p.segment) === null || _b === void 0 ? void 0 : _b.query(p.value) : undefined; })) === null || _a === void 0 ? void 0 : _a.join('&');
const q = (_a = this.props.mapDefined(p => { var _a, _b; return (((_a = p.segment) === null || _a === void 0 ? void 0 : _a.query) ? (_b = p.segment) === null || _b === void 0 ? void 0 : _b.query(p.value) : undefined); })) === null || _a === void 0 ? void 0 : _a.join('&');
this.props = List_1.list();

@@ -39,0 +47,0 @@ return Is_1.isNotEmpty(q) ? `${route}?${q}` : route;

@@ -5,4 +5,4 @@ "use strict";

const IsA_1 = require("./IsA");
const isValidatable = (v) => IsA_1.isA(v, "isValid");
const isValidatable = (v) => IsA_1.isA(v, 'isValid');
exports.isValidatable = isValidatable;
//# sourceMappingURL=Validatable.js.map

@@ -18,7 +18,13 @@ "use strict";

}
else(alt) { return types_1.ofGet(alt, this.value); }
else(alt) {
return types_1.ofGet(alt, this.value);
}
}
class Found extends Case {
case(pred, out) { return this; }
else(alt) { return this.outcome; }
case(pred, out) {
return this;
}
else(alt) {
return this.outcome;
}
}

@@ -25,0 +31,0 @@ exports.Found = Found;

@@ -1,2 +0,2 @@

export * from "./Case";
export * from "./Promise";
export * from './Case';
export * from './Promise';
import { Results, Text } from '../types';
export declare const resolve: <S>(subject: S | PromiseLike<S>) => Promise<S>;
export declare const reject: (e: Text | Error | Results) => Promise<never>;
export declare const reject: <S>(e: Text | Error | Results) => Promise<S>;

@@ -1,3 +0,4 @@

export * from "./Contraints";
export * from "./Validate";
export * from "./When";
export * from './Contraints';
export * from './Match';
export * from './Validate';
export * from './When';

@@ -14,4 +14,5 @@ "use strict";

__exportStar(require("./Contraints"), exports);
__exportStar(require("./Match"), exports);
__exportStar(require("./Validate"), exports);
__exportStar(require("./When"), exports);
//# sourceMappingURL=index.js.map

@@ -7,4 +7,5 @@ import { Results, Text } from '../types';

message: Text;
actual?: unknown;
};
export declare const validate: (subject?: unknown) => Results;
export declare const validateReject: <T>(subject: T) => Promise<T>;

@@ -6,11 +6,16 @@ "use strict";

const When_1 = require("./When");
const parse = (subject, v) => types_1.result(v.message.toString()
const parse = (subject, v) => types_1.result(v.message
.toString()
.replace('$subject', subject.constructor.name)
.replace('$property', `property '${v.property}'`)
.replace('$actual', `'${subject[v.property]}'`), subject.constructor.name, v.property);
.replace('$property', `Property '${v.property}'`)
.replace('$actual', `Value '${v.actual}' for property '${v.property}'`), subject.constructor.name, v.property);
const validate = (subject) => {
return (!types_1.isDefined(subject))
? types_1.results('Object can not be validated')
: types_1.meta(subject).keys('constraint')
.mapDefined(v => !v.constraint(subject[v.property]) ? parse(subject, v) : undefined)
return !types_1.isDefined(subject)
? types_1.results('Subject can not be validated')
: types_1.meta(subject)
.keys('constraint')
.mapDefined(v => {
v.actual = subject[v.property];
return !v.constraint(v.actual) ? parse(subject, v) : undefined;
})
.reduce((rs, r) => rs.add(r), types_1.results());

@@ -17,0 +22,0 @@ };

@@ -16,10 +16,18 @@ "use strict";

this.is = (item) => this.clone(this.invalid === (this.subject === item));
this.reject = (error) => { var _a; return !this.invalid ? utils_1.resolve(this.subject) : utils_1.reject((_a = this.results) !== null && _a !== void 0 ? _a : error); };
this.reject = (error) => { var _a; return (!this.invalid ? utils_1.resolve(this.subject) : utils_1.reject((_a = this.results) !== null && _a !== void 0 ? _a : error)); };
this.recover = (f) => utils_1.resolve(!this.invalid ? this.subject : f(this.subject));
this.clone = (result = true) => new When(this.subject, result, this.results);
}
get not() { return this.clone(!this.invalid); }
get isDefined() { return this.clone(this.invalid === types_1.isDefined(this.subject)); }
get isEmpty() { return this.clone(this.invalid === types_1.isEmpty(this.subject)); }
get isTrue() { return this.clone(this.invalid === !!this.subject); }
get not() {
return this.clone(!this.invalid);
}
get isDefined() {
return this.clone(this.invalid === types_1.isDefined(this.subject));
}
get isEmpty() {
return this.clone(this.invalid === types_1.isEmpty(this.subject));
}
get isTrue() {
return this.clone(this.invalid === !!this.subject);
}
get isValid() {

@@ -26,0 +34,0 @@ this.results = Validate_1.validate(this.subject);

{
"name": "@thisisagile/easy",
"version": "1.14.4",
"version": "1.14.5",
"description": "Straightforward library for building domain-driven microservice architectures",

@@ -20,2 +20,6 @@ "author": "Sander Hoogendoorn",

"scripts": {
"lint": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"postlint": "npm run format",
"format": "prettier --write src test *.js *.json",
"prebuild": "npm run lint",
"build": "tsc",

@@ -35,5 +39,5 @@ "pretest": "jest --clearCache",

"devDependencies": {
"@thisisagile/easy-test": "^1.4.0",
"@types/express": "^4.17.9",
"@types/uuid": "^8.3.0",
"@thisisagile/easy-test": "^1.4.0",
"prettier": "^2.2.1",

@@ -40,0 +44,0 @@ "semantic-release": "^17.3.0",

@@ -1,1 +0,1 @@

export * from "./Query";
export * from './Query';

@@ -1,2 +0,2 @@

import { Json, JsonValue } from "../types";
import { Json, JsonValue } from '../types';

@@ -9,2 +9,2 @@ export class Query {

export const where = (key: string, value: JsonValue) => new Query(key, value);
export const where = (key: string, value: JsonValue): Query => new Query(key, value);

@@ -1,3 +0,3 @@

export * from "./Entity";
export * from "./Record";
export * from "./Repo";
export * from './Entity';
export * from './Record';
export * from './Repo';

@@ -5,11 +5,13 @@ import { Json, jsonify, Validatable } from '../types';

export abstract class Record implements Validatable {
constructor(protected readonly state: any = {}) {}
constructor(protected readonly state: any = {}) {}
get isValid(): boolean { return validate(this).isValid; }
get isValid(): boolean {
return validate(this).isValid;
}
toJSON(): Json {
return jsonify({ ...this, state: undefined });
}
toJSON(): Json {
return jsonify({ ...this, state: undefined });
}
update = (json: Json): this => this;
update = (json: Json): this => this;
}

@@ -15,3 +15,4 @@ import { Constructor, Gateway, Id, Json, jsonify, JsonValue, List } from '../types';

add = (json: Json): Promise<T> =>
when(new this.ctor(json)).not.isValid.reject()
when(new this.ctor(json))
.not.isValid.reject()
.then(i => this.validate(i))

@@ -22,5 +23,6 @@ .then(i => this.gateway.add(jsonify(i)))

update = (json: Json): Promise<T> =>
this.gateway.byId(json.id as Id)
this.gateway
.byId(json.id as Id)
.then(j => when(j).not.isDefined.reject('Does not exist'))
.then(j => (new this.ctor(j)).update(j))
.then(j => new this.ctor(j).update(j))
.then(i => when(i).not.isValid.reject())

@@ -34,2 +36,1 @@ .then(i => this.gateway.update(i.toJSON()))

}

@@ -7,5 +7,6 @@ import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';

const handle = (endpoint: Endpoint): RequestHandler =>
(req: Request, res: Response, next: NextFunction) =>
endpoint(toReq(req)).then((r: any) => res.status(200).json(toRestResult(r))).catch(next);
const handle = (endpoint: Endpoint): RequestHandler => (req: Request, res: Response, next: NextFunction) =>
endpoint(toReq(req))
.then((r: any) => res.status(200).json(toRestResult(r)))
.catch(next);

@@ -15,4 +16,7 @@ export class ExpressProvider implements AppProvider {

listen = (port: number, message: string = `Service is listening on port ${port}.`) =>
this.app.listen(port, () => { console.log(message); });
listen = (port: number, message = `Service is listening on port ${port}.`): void => {
this.app.listen(port, () => {
console.log(message);
});
};

@@ -23,7 +27,7 @@ use = (h: RequestHandler): void => {

route = (resource: Constructor) => {
route = (resource: Constructor): void => {
const { route, endpoints } = routes(resource);
const router = express.Router({ mergeParams: true });
endpoints.forEach(({ endpoint, verb }: { endpoint: Endpoint, verb: HttpVerb }) => {
endpoints.forEach(({ endpoint, verb }: { endpoint: Endpoint; verb: HttpVerb }) => {
console.log(verb.code, route.path);

@@ -30,0 +34,0 @@ router[verb.toString() as ExpressVerb](route.path, handle(endpoint));

@@ -1,1 +0,1 @@

export * from "./ExpressProvider";
export * from './ExpressProvider';

@@ -1,8 +0,8 @@

export * from "./data";
export * from "./domain";
export * from "./express";
export * from "./process";
export * from "./services";
export * from "./types";
export * from "./utils";
export * from "./validation";
export * from './data';
export * from './domain';
export * from './express';
export * from './process';
export * from './services';
export * from './types';
export * from './utils';
export * from './validation';

@@ -1,2 +0,2 @@

export * from "./Manage";
export * from "./Select";
export * from './Manage';
export * from './Select';

@@ -6,3 +6,2 @@ import { Select } from './Select';

export class Manage<T extends Record> extends Select<T> {
add = (json: Json): Promise<T> => this.repo.add(json);

@@ -9,0 +8,0 @@ update = (json: Json): Promise<T> => this.repo.update(json);

@@ -6,3 +6,3 @@ import { Constructor } from '../types';

route: (r: Constructor) => void;
listen: (port: number) => void
listen: (port: number) => void;
}

@@ -9,7 +9,12 @@ import axios, { AxiosError, Method } from 'axios';

const toResult = (uri: Uri, verb: HttpVerb, error: AxiosError): Result =>
choose<Result, AxiosError>(error)
.case(e => isDefined(e.response), e => result(e.response.statusText, verb.toString(), uri.toString()))
.case(e => isDefined(e.request), e => result(e.request.statusText, verb.toString(), uri.toString()))
.case(
e => isDefined(e.response),
e => result(e.response.statusText, verb.toString(), uri.toString())
)
.case(
e => isDefined(e.request),
e => result(e.request.statusText, verb.toString(), uri.toString())
)
.else(e => result(e.message, verb.toString(), uri.toString()));

@@ -19,8 +24,9 @@

execute = ({ uri, verb, body, transform = (r: any) => r, options = RequestOptions.Json }: Request): Promise<RestResult> =>
axios.request({
url: uri.toString(),
method: verb.toString() as Method,
headers: options.headers,
data: body
})
axios
.request({
url: uri.toString(),
method: verb.toString() as Method,
headers: options.headers,
data: body,
})
.then(r => transform(r))

@@ -27,0 +33,0 @@ .catch(e => toResult(uri, verb, e))

import { Enum, Get, isDefined, Json, ofGet } from '../types';
const formEncode = (body: unknown): string =>
Object.entries(body).map(([key, value]) => `${key}=${value}`).join("&");
Object.entries(body)
.map(([key, value]) => `${key}=${value}`)
.join('&');

@@ -9,8 +11,7 @@ const jsonEncode = (body: unknown): string => JSON.stringify(body);

export class ContentType extends Enum {
static Json = new ContentType('json', 'application/json', b => jsonEncode(b));
static Text = new ContentType('text', 'text/plain', b => b.toString());
static Xml = new ContentType('xml', 'application/xml');
static Form = new ContentType('form', 'application/x-www-form-urlencoded', b => formEncode(b));
static Json = new ContentType("json", "application/json", b => jsonEncode(b));
static Text = new ContentType("text", "text/plain", b => b.toString());
static Xml = new ContentType("xml", "application/xml");
static Form = new ContentType("form", "application/x-www-form-urlencoded", b => formEncode(b));
private constructor(name: string, readonly type: string, private readonly encoder?: Get<string>) {

@@ -20,3 +21,3 @@ super(name, type);

encode = (body?: Json): string => isDefined(body) ? ofGet(this.encoder, body) : undefined;
encode = (body?: Json): string => (isDefined(body) ? ofGet(this.encoder, body) : undefined);
}

@@ -1,21 +0,23 @@

import {Enum} from '../types';
import { Enum } from '../types';
export class HttpStatus extends Enum {
static Ok = new HttpStatus("Ok", 200);
static Created = new HttpStatus("Created", 201);
static NoContent = new HttpStatus("No content", 204);
static BadRequest = new HttpStatus("Bad request", 400);
static NotAuthorized = new HttpStatus("Not authorized", 401);
static Forbidden = new HttpStatus("Forbidden", 403);
static NotFound = new HttpStatus("Not found", 404);
static Conflict = new HttpStatus("Conflict", 409);
static InternalServerError = new HttpStatus("Internal server error", 500);
static NotImplemented = new HttpStatus("Not implemented", 501);
static BadGateway = new HttpStatus("Bad gateway", 502);
static Ok = new HttpStatus('Ok', 200);
static Created = new HttpStatus('Created', 201);
static NoContent = new HttpStatus('No content', 204);
static BadRequest = new HttpStatus('Bad request', 400);
static NotAuthorized = new HttpStatus('Not authorized', 401);
static Forbidden = new HttpStatus('Forbidden', 403);
static NotFound = new HttpStatus('Not found', 404);
static Conflict = new HttpStatus('Conflict', 409);
static InternalServerError = new HttpStatus('Internal server error', 500);
static NotImplemented = new HttpStatus('Not implemented', 501);
static BadGateway = new HttpStatus('Bad gateway', 502);
get isError(): boolean {
return this.id >= 400;
}
get isError(): boolean {
return this.id >= 400;
}
get status(): number { return this.id as number }
get status(): number {
return this.id as number;
}
}

@@ -10,3 +10,5 @@ import { Enum } from '../types';

constructor(name: string) {super(name, name.toLowerCase(), name.toUpperCase()); }
constructor(name: string) {
super(name, name.toLowerCase(), name.toUpperCase());
}
}

@@ -1,15 +0,13 @@

export * from "./Api";
export * from "./AppProvider";
export * from "./AxiosProvider";
export * from "./ContentType";
export * from "./EasyResponse";
export * from "../express/ExpressProvider";
export * from "./HttpStatus";
export * from "./HttpVerb";
export * from "./Req";
export * from "./RequestOptions";
export * from "./RequestProvider";
export * from "./RestResult";
export * from "./Route";
export * from "./RouteGateway";
export * from "./Verb";
export * from './Api';
export * from './AppProvider';
export * from './AxiosProvider';
export * from './ContentType';
export * from './HttpStatus';
export * from './HttpVerb';
export * from './Req';
export * from './RequestOptions';
export * from './RequestProvider';
export * from './RestResult';
export * from './Route';
export * from './RouteGateway';
export * from './Verb';
import { Id, Json, JsonValue } from '../types';
export type Req = {path?: Json, id?: Id, query?: Json, q?: JsonValue, body?: Json };
export type Req = { path?: Json; id?: Id; query?: Json; q?: JsonValue; body?: Json };
export const toReq = (req: any): Req => ({
export const toReq = (req: { params?: { id?: unknown }; query?: { q?: unknown }; body?: unknown }): Req => ({
path: req.params as Json,
id: req.params?.id as Id,
id: req.params?.id as Id,
query: req.query as Json,
q: req.query?.q as Json,
body: req.body as Json
body: req.body as Json,
});
import { ContentType } from './ContentType';
import { Enum, isNotEmpty, JsonValue } from '../types';
export class RequestOptions extends Enum {
static Json = new RequestOptions(ContentType.Json);

@@ -29,5 +27,7 @@ static Text = new RequestOptions(ContentType.Text);

bearer = (jwt: JsonValue): this => {
if (isNotEmpty(jwt)) { this.authorization(`Bearer ${jwt}`); }
if (isNotEmpty(jwt)) {
this.authorization(`Bearer ${jwt}`);
}
return this;
};
}

@@ -7,8 +7,8 @@ import { Json, Uri } from '../types';

export type Request = {
uri: Uri,
verb: HttpVerb,
body?: Json,
transform?: (r: any) => any,
options?: RequestOptions
}
uri: Uri;
verb: HttpVerb;
body?: Json;
transform?: (r: any) => any;
options?: RequestOptions;
};

@@ -15,0 +15,0 @@ export interface RequestProvider {

@@ -6,5 +6,5 @@ import { isDefined, isResult, Json, list, List, Result, toList } from '../types';

export type RestResult = {
data?: { code: number, items: List<Json>; itemCount: number; },
error?: { code: number; message: string, errorCount: number, errors: List<Result>; }
}
data?: { code: number; items: List<Json>; itemCount: number };
error?: { code: number; message: string; errorCount: number; errors: List<Result> };
};

@@ -16,3 +16,3 @@ const data = (items?: Json[]): RestResult => ({

itemCount: items.length,
}
},
});

@@ -26,14 +26,25 @@

errorCount: errors.length,
}
},
});
export const isRestResult = (r: unknown): r is RestResult =>
isDefined(r) && (isDefined((r as RestResult).data) || isDefined((r as RestResult).error));
export const isRestResult = (r: unknown): r is RestResult => isDefined(r) && (isDefined((r as RestResult).data) || isDefined((r as RestResult).error));
export const toRestResult = (payload?: any | any[]): RestResult =>
choose<RestResult, any>(payload)
.case(p => !p, () => data())
.case(p => isResult(p), p => error([p]))
.case(p => p.error && p.error.errors, p => error(p.error.errors))
.case(p => p.data && p.data.items, p => data(p.data.items))
.case(
p => !p,
() => data()
)
.case(
p => isResult(p),
p => error([p])
)
.case(
p => p.error && p.error.errors,
p => error(p.error.errors)
)
.case(
p => p.data && p.data.items,
p => data(p.data.items)
)
.else(p => data(toList(p)));

@@ -6,14 +6,18 @@ import { Constructor, List, meta, Uri } from '../types';

export const route = (uri: Uri): ClassDecorator =>
(subject: Function): void => { meta(subject).set('route', uri); };
export const route = (uri: Uri): ClassDecorator => (subject: unknown): void => {
meta(subject).set('route', uri);
};
export type Endpoint<T = unknown> = (re: Req) => Promise<T | List<T>>;
class Routes<T> {
class Routes {
constructor(readonly resource: unknown) {}
get route(): Uri { return meta(this.resource).get('route'); }
get route(): Uri {
return meta(this.resource).get('route');
}
get endpoints(): List<{ verb: HttpVerb, endpoint: Endpoint }> {
return meta(this.resource).properties('verb')
get endpoints(): List<{ verb: HttpVerb; endpoint: Endpoint }> {
return meta(this.resource)
.properties('verb')
.map(p => ({ verb: p.get<Verb>('verb').verb, endpoint: (this.resource as any)[p.property] }));

@@ -23,2 +27,2 @@ }

export const routes = <T>(resource: Constructor<T>) => new Routes<T>(new resource());
export const routes = (resource: Constructor): Routes => new Routes(new resource());
import { Api } from './Api';
import { Gateway, Id, Json, JsonValue, Uri } from '../types';
import { List } from '../types/List';
import { Gateway, Id, Json, JsonValue, List, Uri } from '../types';
export class RouteGateway implements Gateway {
readonly route: Uri;

@@ -8,0 +6,0 @@ readonly routeId: Uri;

@@ -5,20 +5,16 @@ import { HttpVerb } from './HttpVerb';

export type Verb = {verb: HttpVerb, onOk: HttpStatus, onError: HttpStatus};
export type Verb = { verb: HttpVerb; onOk: HttpStatus; onError: HttpStatus };
const verb = <T>(v: Verb): PropertyDecorator =>
(subject: unknown, property: string): void => { meta(subject).property(property).set('verb', v); };
const verb = <T>(v: Verb): PropertyDecorator => (subject: unknown, property: string): void => {
meta(subject).property(property).set('verb', v);
};
export const get = (onOk = HttpStatus.Ok, onError = HttpStatus.NotFound): PropertyDecorator =>
verb({ verb: HttpVerb.Get, onOk, onError });
export const get = (onOk = HttpStatus.Ok, onError = HttpStatus.NotFound): PropertyDecorator => verb({ verb: HttpVerb.Get, onOk, onError });
export const put = (onOk = HttpStatus.Ok, onError = HttpStatus.BadRequest): PropertyDecorator =>
verb({ verb: HttpVerb.Put, onOk, onError });
export const put = (onOk = HttpStatus.Ok, onError = HttpStatus.BadRequest): PropertyDecorator => verb({ verb: HttpVerb.Put, onOk, onError });
export const patch = (onOk = HttpStatus.Ok, onError = HttpStatus.BadRequest): PropertyDecorator =>
verb({ verb: HttpVerb.Patch, onOk, onError });
export const patch = (onOk = HttpStatus.Ok, onError = HttpStatus.BadRequest): PropertyDecorator => verb({ verb: HttpVerb.Patch, onOk, onError });
export const post = (onOk = HttpStatus.Created, onError = HttpStatus.BadRequest): PropertyDecorator =>
verb({ verb: HttpVerb.Post, onOk, onError });
export const post = (onOk = HttpStatus.Created, onError = HttpStatus.BadRequest): PropertyDecorator => verb({ verb: HttpVerb.Post, onOk, onError });
export const del = (onOk = HttpStatus.NoContent, onError = HttpStatus.BadRequest): PropertyDecorator =>
verb({ verb: HttpVerb.Delete, onOk, onError });
export const del = (onOk = HttpStatus.NoContent, onError = HttpStatus.BadRequest): PropertyDecorator => verb({ verb: HttpVerb.Delete, onOk, onError });
import { isArray, isDefined } from './Is';
export const toArray = <T>(...items: (T | T[])[]): T[] =>
(items.length > 1) ? items as T[] : isArray(items[0]) ? items[0] : isDefined(items[0]) ? [items[0]] : [];
items.length > 1 ? (items as T[]) : isArray(items[0]) ? items[0] : isDefined(items[0]) ? [items[0]] : [];

@@ -7,5 +7,5 @@ import { isFunction } from './Is';

export type Predicate<Param> = Get<boolean, Param>;
export const ofGet = <T, Param>(g: Get<T, Param>, ...params: Param[]): T => isFunction(g) ? g(...params) : g;
export const ofGet = <T, Param>(g: Get<T, Param>, ...params: Param[]): T => (isFunction(g) ? g(...params) : g);
export type GetProperty<T, U> = keyof T | ((t: T) => U);
export const ofProperty = <T, U>(t: T, p: GetProperty<T, U>): U => isFunction(p) ? p(t) : t[p] as unknown as U;
export const ofProperty = <T, U>(t: T, p: GetProperty<T, U>): U => (isFunction(p) ? p(t) : ((t[p] as unknown) as U));

@@ -13,14 +13,24 @@ import { Id } from './Id';

static all<E extends Enum>(): List<E> {
return meta(this).values().filter((e: unknown) => isEnum(e));
return meta(this)
.values()
.filter((e: unknown) => isEnum(e));
}
static byId<E extends Enum>(id: Id, alt?: Get<E>): E {
return meta(this).values().first((e: unknown) => isEnum(e) && e.id === id) ?? ofGet(alt);
return (
meta(this)
.values()
.first((e: unknown) => isEnum(e) && e.id === id) ?? ofGet(alt)
);
}
get isValid(): boolean { return isDefined(this.id); }
get isValid(): boolean {
return isDefined(this.id);
}
toString(): string { return this.id.toString(); }
toString(): string {
return this.id.toString();
}
}
export const isEnum = (e?: unknown): e is Enum => isDefined(e) && (e instanceof Enum) && isAn<Enum>(e, 'name', 'id', 'code');
export const isEnum = (e?: unknown): e is Enum => isDefined(e) && e instanceof Enum && isAn<Enum>(e, 'name', 'id', 'code');

@@ -1,2 +0,2 @@

import { v4 as uuid } from "uuid";
import { v4 as uuid } from 'uuid';

@@ -3,0 +3,0 @@ export type Id = string | number;

@@ -1,20 +0,20 @@

export * from "./Array";
export * from "./Constructor";
export * from "./Enum";
export * from "./Gateway";
export * from "./Id";
export * from "./Is";
export * from "./IsA";
export * from "./IsDate";
export * from "./Json";
export * from "./List";
export * from "./Message";
export * from "./Meta";
export * from "./Result";
export * from "./Results";
export * from "./Text";
export * from "./Uri";
export * from "./Validatable";
export * from './Array';
export * from './Constructor';
export * from './Enum';
export * from './Gateway';
export * from './Id';
export * from './Is';
export * from './IsA';
export * from './IsDate';
export * from './Json';
export * from './List';
export * from './Message';
export * from './Meta';
export * from './Result';
export * from './Results';
export * from './Text';
export * from './Uri';
export * from './Validatable';
export { inFuture } from './IsDate';
export { inPast } from './IsDate';
export { isDate } from './IsDate';

@@ -11,3 +11,3 @@ import { Constructor } from './Constructor';

export const isObject = (o?: unknown): o is Object => o != null && (typeof o === 'object' || typeof o === 'function') && !isArray(o);
export const isObject = (o?: unknown): boolean => o != null && (typeof o === 'object' || typeof o === 'function') && !isArray(o);

@@ -24,3 +24,2 @@ export const isEmptyObject = (o?: unknown): boolean => isObject(o) && Object.getOwnPropertyNames(o).length === 0;

export const isPrimitive = (o?: unknown): boolean => (o !== null) && !isObject(o) && !isFunction(o) && !isArray(o);
export const isPrimitive = (o?: unknown): boolean => o !== null && !isObject(o) && !isFunction(o) && !isArray(o);

@@ -1,2 +0,2 @@

import { isDefined } from "./Is";
import { isDefined } from './Is';

@@ -6,2 +6,2 @@ export const isA = <T>(t?: unknown, ...properties: (keyof T)[]): t is T => isDefined(t) && properties.every(p => isDefined((t as T)[p]));

export const isError = (e: unknown): e is Error => isAn<Error>(e, "name", "message");
export const isError = (e: unknown): e is Error => isAn<Error>(e, 'name', 'message');

@@ -1,6 +0,4 @@

export const isDate = (o?: unknown): o is Date => o instanceof Date && !isNaN(o.getTime());
export const days = {
add: (date: Date, days: number): Date => {

@@ -12,4 +10,4 @@ date.setDate(date.getDate() + days);

yesterday: (): Date => days.add(days.today(), -1),
tomorrow: (): Date => days.add(days.today(), 1)
}
tomorrow: (): Date => days.add(days.today(), 1),
};

@@ -16,0 +14,0 @@ export const inPast = (o?: unknown): boolean => isDate(o) && o <= days.today();

export type JsonValue = string | number | boolean | null | Json | JsonValue[];
export type Json = { [key: string]: JsonValue };
export const jsonify = (subject: unknown = {}, additional?: Json): Json =>
({ ...(JSON.parse(JSON.stringify(subject))), ...additional });
export const jsonify = (subject: unknown = {}, additional?: Json): Json => ({ ...JSON.parse(JSON.stringify(subject)), ...additional });

@@ -8,25 +8,17 @@ import { toArray } from './Array';

export class List<T> extends Array<T> {
asc = (p: GetProperty<T, any>): List<T> => this.sort((e1, e2) => (ofProperty(e1, p) > ofProperty(e2, p) ? 1 : -1));
asc = (p: GetProperty<T, any>): List<T> =>
this.sort((e1, e2) => (ofProperty(e1, p) > ofProperty(e2, p) ? 1 : -1));
desc = (p: GetProperty<T, any>): List<T> => this.sort((e1, e2) => (ofProperty(e1, p) < ofProperty(e2, p) ? 1 : -1));
desc = (p: GetProperty<T, any>): List<T> =>
this.sort((e1, e2) => (ofProperty(e1, p) < ofProperty(e2, p) ? 1 : -1));
first = (p?: (value: T, index: number, array: T[]) => unknown, params?: unknown): T => (p ? this.filter(p, params).first() : this[0]);
first = (p?: (value: T, index: number, array: T[]) => unknown, params?: any): T =>
p ? this.filter(p, params).first() : this[0];
last = (p?: (value: T, index: number, array: T[]) => unknown, params?: unknown): T => (p ? this.filter(p, params).last() : this[this.length - 1]);
last = (p?: (value: T, index: number, array: T[]) => unknown, params?: any): T =>
p ? this.filter(p, params).last() : this[this.length - 1];
toJSON = (): List<Json> => this.map(i => jsonify(i));
map = <U>(f: (value: T, index: number, array: T[]) => U, params?: any): List<U> =>
super.map(f, params) as List<U>;
map = <U>(f: (value: T, index: number, array: T[]) => U, params?: unknown): List<U> => super.map(f, params) as List<U>;
mapDefined = <U>(f: (value: T, index: number, array: T[]) => U, params?: any): List<U> =>
this.map(f, params).filter(i => isDefined(i));
mapDefined = <U>(f: (value: T, index: number, array: T[]) => U, params?: unknown): List<U> => this.map(f, params).filter(i => isDefined(i));
filter = (p: (value: T, index: number, array: T[]) => unknown, params?: any): List<T> =>
super.filter(p, params) as List<T>;
filter = (p: (value: T, index: number, array: T[]) => unknown, params?: unknown): List<T> => super.filter(p, params) as List<T>;

@@ -38,3 +30,3 @@ concat = (...items: (T | ConcatArray<T>)[]): List<T> => super.concat(...items) as List<T>;

return this;
}
};
}

@@ -44,4 +36,4 @@

export const toList = <T>(...items: (T | T[])[]): List<T> => (items.length > 1) ? list<T>(...items) : list<T>(items[0]);
export const toList = <T>(...items: (T | T[])[]): List<T> => (items.length > 1 ? list<T>(...items) : list<T>(items[0]));
export const isList = <T>(l?: unknown): l is List<T> => isDefined(l) && isArray(l) && isA<List<T>>(l, 'first', 'last', 'asc', 'desc');

@@ -18,6 +18,8 @@ import 'reflect-metadata';

.map(p => this.property(p))
.filter(p => key ? p.get(key) : p);
.filter(p => (key ? p.get(key) : p));
keys = <T = any>(key: string): List<T> =>
this.properties().map(p => p.get<T>(key)).filter(v => isDefined(v));
this.properties()
.map(p => p.get<T>(key))
.filter(v => isDefined(v));

@@ -32,5 +34,7 @@ values = () => this.properties().map(p => p.value);

get value(): any { return (this.subject as any)[this.property]; }
get value(): any {
return (this.subject as any)[this.property];
}
get = <T>(key: string): T => isDefined(this.data) && isDefined(this.data[key]) ? this.data[key] as T : undefined;
get = <T>(key: string): T => (isDefined(this.data) && isDefined(this.data[key]) ? (this.data[key] as T) : undefined);

@@ -37,0 +41,0 @@ set = <T>(key: string, value: T): T => {

@@ -1,8 +0,8 @@

import { isA } from "./IsA";
import { isA } from './IsA';
import { Text } from './Text';
export type Result = { message: Text, domain?: string, location?: string };
export type Result = { message: Text; domain?: string; location?: string };
export const result = (message: Text, domain: string = "easy", location?: string) => ({ message, domain, location });
export const result = (message: Text, domain = 'easy', location?: string): Result => ({ message, domain, location });
export const isResult = (r?: unknown): r is Result => isA<Result>(r, "message");
export const isResult = (r?: unknown): r is Result => isA<Result>(r, 'message');

@@ -6,3 +6,3 @@ import { Text } from './Text';

const parse = (...rs: (Text | Result)[]): Result[] => rs.map(r => isResult(r) ? r : result(r.toString(), 'easy'));
const parse = (...rs: (Text | Result)[]): Result[] => rs.map(r => (isResult(r) ? r : result(r.toString(), 'easy')));

@@ -16,5 +16,9 @@ export class Results implements Validatable {

get length(): number { return this.results.length; }
get length(): number {
return this.results.length;
}
get isValid(): boolean { return this.results.length === 0; }
get isValid(): boolean {
return this.results.length === 0;
}

@@ -21,0 +25,0 @@ add = (...rs: (Text | Result)[]): Results => results(...this.results, ...parse(...rs));

@@ -1,5 +0,5 @@

import { isA } from "./IsA";
import { isA } from './IsA';
export type Text = { toString(): string };
export const isText = (t?: unknown): t is Text => isA<Text>(t, "toString");
export const isText = (t?: unknown): t is Text => isA<Text>(t, 'toString');
import { isNotEmpty } from './Is';
import { list } from './List';
export type Segment = { key: string, segment?: string, query?: (value: unknown) => string };
export type Segment = { key: string; segment?: string; query?: (value: unknown) => string };

@@ -13,12 +13,14 @@ const name = (name?: string): string => name?.replace('Uri', '').toLowerCase();

path: (key: string): Segment => ({ key, segment: `:${key}` }),
query: (key: string): Segment => ({ key, query: (value: unknown): string => value ? `${key}=${value}` : undefined }),
query: (key: string): Segment => ({ key, query: (value: unknown): string => (value ? `${key}=${value}` : undefined) }),
};
type Prop = { segment: Segment, value: unknown };
type Prop = { segment: Segment; value: unknown };
const toRoute = (...segments: Segment[]): string => list(...segments).mapDefined(s => s.segment).join('/');
const toRoute = (...segments: Segment[]): string =>
list(...segments)
.mapDefined(s => s.segment)
.join('/');
const parse = (route: string, p: Prop): string => route.replace(p.segment.segment, p.value.toString());
export class Uri {
static readonly id = uri.path('id');

@@ -32,7 +34,13 @@ static readonly query = uri.query('q');

get route(): string { return toRoute(uri.segment(''), ...this.segments); }
get route(): string {
return toRoute(uri.segment(''), ...this.segments);
}
get path(): string { return toRoute(uri.segment(''), this.resource, ...this.segments); }
get path(): string {
return toRoute(uri.segment(''), this.resource, ...this.segments);
}
get complete(): string { return toRoute(this.host, this.resource, ...this.segments); }
get complete(): string {
return toRoute(this.host, this.resource, ...this.segments);
}

@@ -46,3 +54,3 @@ set = (segment: Segment, value: unknown): this => {

const route = this.props.reduce((r: string, p: Prop) => parse(r, p), this.complete);
const q = this.props.mapDefined(p => p.segment?.query ? p.segment?.query(p.value) : undefined)?.join('&');
const q = this.props.mapDefined(p => (p.segment?.query ? p.segment?.query(p.value) : undefined))?.join('&');
this.props = list<Prop>();

@@ -49,0 +57,0 @@ return isNotEmpty(q) ? `${route}?${q}` : route;

@@ -1,2 +0,2 @@

import { isA } from "./IsA";
import { isA } from './IsA';

@@ -7,2 +7,2 @@ export interface Validatable {

export const isValidatable = (v?: unknown): v is Validatable => isA<Validatable>(v, "isValid");
export const isValidatable = (v?: unknown): v is Validatable => isA<Validatable>(v, 'isValid');

@@ -14,11 +14,17 @@ import { Get, ofGet, Predicate } from '../types';

else(alt?: Get<T, V>): T { return ofGet(alt, this.value); }
else(alt?: Get<T, V>): T {
return ofGet(alt, this.value);
}
}
export class Found<T, V = unknown> extends Case<T, V> {
case(pred: Predicate<V>, out: Get<T, V>): this { return this; }
case(pred: Predicate<V>, out: Get<T, V>): this {
return this;
}
else(alt?: Get<T, V>): T { return this.outcome; }
else(alt?: Get<T, V>): T {
return this.outcome;
}
}
export const choose = <T, V = unknown>(value: V): Case<T, V> => new Case(value);

@@ -1,2 +0,2 @@

export * from "./Case";
export * from "./Promise";
export * from './Case';
export * from './Promise';
import { isError, isText, results, Results, Text } from '../types';
export const resolve = <S>(subject: S | PromiseLike<S>): Promise<S> => Promise.resolve(subject);
export const reject = (e: Text | Error | Results) => Promise.reject(isError(e) ? e : isText(e) ? results(e) : e);
export const reject = <S>(e: Text | Error | Results): Promise<S> => Promise.reject(isError(e) ? e : isText(e) ? results(e) : e);

@@ -6,15 +6,11 @@ import { inFuture, inPast, isDefined, isIn, isString, meta, Text } from '../types';

export const constraint = <T>(c: Constraint, message: Text): PropertyDecorator =>
(subject: unknown, property: string): void => {
meta(subject).property(property).set('constraint', { property, constraint: c, message });
};
export const constraint = <T>(c: Constraint, message: Text): PropertyDecorator => (subject: unknown, property: string): void => {
meta(subject).property(property).set('constraint', { property, constraint: c, message });
};
export const defined = (message?: Text): PropertyDecorator =>
constraint(v => isDefined(v), message ?? '$property must be defined.');
export const defined = (message?: Text): PropertyDecorator => constraint(v => isDefined(v), message ?? '$property must be defined.');
export const required = (message?: Text): PropertyDecorator =>
constraint(v => isDefined(v), message ?? '$property is required.');
export const required = (message?: Text): PropertyDecorator => constraint(v => isDefined(v), message ?? '$property is required.');
export const valid = (message?: Text): PropertyDecorator =>
constraint(v => validate(v).isValid, message ?? '$property must be valid.');
export const valid = (message?: Text): PropertyDecorator => constraint(v => validate(v).isValid, message ?? '$property must be valid.');

@@ -27,4 +23,3 @@ export const includes = (sub: string, message?: string): PropertyDecorator =>

export const gt = (limit: number, message?: Text): PropertyDecorator =>
constraint(v => v > limit, message ?? `$actual must be larger than '${limit}'.`);
export const gt = (limit: number, message?: Text): PropertyDecorator => constraint(v => v > limit, message ?? `$actual must be larger than '${limit}'.`);

@@ -34,4 +29,3 @@ export const gte = (limit: number, message?: Text): PropertyDecorator =>

export const lt = (limit: number, message?: Text): PropertyDecorator =>
constraint(v => v < limit, message ?? `$actual must be smaller than ${limit}.`);
export const lt = (limit: number, message?: Text): PropertyDecorator => constraint(v => v < limit, message ?? `$actual must be smaller than ${limit}.`);

@@ -41,7 +35,4 @@ export const lte = (limit: number, message?: Text): PropertyDecorator =>

export const past = (message?: Text): PropertyDecorator =>
constraint(v => inPast(v), message ?? '$actual must lay in the past.');
export const past = (message?: Text): PropertyDecorator => constraint(v => inPast(v), message ?? '$actual must lay in the past.');
export const future = (message?: Text): PropertyDecorator =>
constraint(v => inFuture(v), message ?? '$actual must lay in the future.');
export const future = (message?: Text): PropertyDecorator => constraint(v => inFuture(v), message ?? '$actual must lay in the future.');

@@ -1,3 +0,4 @@

export * from "./Contraints";
export * from "./Validate";
export * from "./When";
export * from './Contraints';
export * from './Match';
export * from './Validate';
export * from './When';

@@ -5,20 +5,27 @@ import { isDefined, meta, result, Result, results, Results, Text } from '../types';

export type Validator = { property: string, constraint: Constraint, message: Text };
export type Validator = { property: string; constraint: Constraint; message: Text; actual?: unknown };
const parse = (subject: unknown, v: Validator): Result =>
result(v.message.toString()
.replace('$subject', subject.constructor.name)
.replace('$property', `property '${v.property}'`)
.replace('$actual', `'${(subject as any)[v.property]}'`),
subject.constructor.name, v.property);
result(
v.message
.toString()
.replace('$subject', subject.constructor.name)
.replace('$property', `Property '${v.property}'`)
.replace('$actual', `Value '${v.actual}' for property '${v.property}'`),
subject.constructor.name,
v.property
);
export const validate = (subject?: unknown): Results => {
return (!isDefined(subject))
? results('Object can not be validated')
: meta(subject).keys<Validator>('constraint')
.mapDefined(v => !v.constraint((subject as any)[v.property]) ? parse(subject, v) : undefined)
.reduce((rs, r) => rs.add(r), results());
return !isDefined(subject)
? results('Subject can not be validated')
: meta(subject)
.keys<Validator>('constraint')
.mapDefined(v => {
v.actual = (subject as any)[v.property];
return !v.constraint(v.actual) ? parse(subject, v) : undefined;
})
.reduce((rs, r) => rs.add(r), results());
};
export const validateReject = <T>(subject: T): Promise<T> =>
when(subject).not.isValid.reject();
export const validateReject = <T>(subject: T): Promise<T> => when(subject).not.isValid.reject();

@@ -6,12 +6,19 @@ import { Constructor, isDefined, isEmpty, isIn, ofGet, Predicate, Results, Text, toArray } from '../types';

class When<T> {
constructor(readonly subject: T, readonly invalid = true, private results?: Results) {}
get not(): When<T> { return this.clone(!this.invalid); }
get not(): When<T> {
return this.clone(!this.invalid);
}
get isDefined(): When<T> { return this.clone(this.invalid === isDefined(this.subject)); }
get isDefined(): When<T> {
return this.clone(this.invalid === isDefined(this.subject));
}
get isEmpty(): When<T> { return this.clone(this.invalid === isEmpty(this.subject)); }
get isEmpty(): When<T> {
return this.clone(this.invalid === isEmpty(this.subject));
}
get isTrue(): When<T> { return this.clone(this.invalid === !!this.subject); }
get isTrue(): When<T> {
return this.clone(this.invalid === !!this.subject);
}

@@ -23,19 +30,13 @@ get isValid(): When<T> {

isInstance = <U>(c: Constructor<U>): When<T> =>
this.clone(this.invalid === this.subject instanceof c);
isInstance = <U>(c: Constructor<U>): When<T> => this.clone(this.invalid === this.subject instanceof c);
with = (pred: Predicate<T>): When<T> =>
this.clone(this.invalid === ofGet(pred, this.subject));
with = (pred: Predicate<T>): When<T> => this.clone(this.invalid === ofGet(pred, this.subject));
in = (...items: T[]): When<T> =>
this.clone(this.invalid === isIn(this.subject, toArray(...items)));
in = (...items: T[]): When<T> => this.clone(this.invalid === isIn(this.subject, toArray(...items)));
is = (item: T): When<T> =>
this.clone(this.invalid === (this.subject === item));
is = (item: T): When<T> => this.clone(this.invalid === (this.subject === item));
reject = (error?: Text | Error): Promise<T> =>
!this.invalid ? resolve(this.subject) : reject(this.results ?? error);
reject = (error?: Text | Error): Promise<T> => (!this.invalid ? resolve(this.subject) : reject(this.results ?? error));
recover = (f: (item: T) => T | Promise<T>): Promise<T> =>
resolve(!this.invalid ? this.subject : f(this.subject));
recover = (f: (item: T) => T | Promise<T>): Promise<T> => resolve(!this.invalid ? this.subject : f(this.subject));

@@ -42,0 +43,0 @@ protected clone = (result = true): When<T> => new When(this.subject, result, this.results);

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc