Skip to content

Commit

Permalink
feat: initial code (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
ForbesLindesay authored Jan 16, 2019
1 parent 3ba4998 commit a8549f7
Show file tree
Hide file tree
Showing 14 changed files with 4,597 additions and 0 deletions.
80 changes: 80 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
version: 2

refs:
container: &container
docker:
- image: node:10
working_directory: ~/repo
steps:
- &Versions
run:
name: Versions
command: node -v && npm -v && yarn -v
- &Install
run:
name: Install Dependencies
command: yarn install --pure-lockfile
- &Build
run:
name: Build
command: yarn build
- &Test
run:
name: Test
command: yarn ci:test

jobs:
test:
<<: *container
steps:
- checkout
- *Versions
- *Install
- *Test
- *Build

publish:
<<: *container
steps:
- checkout
- *Versions
- *Install
- *Test
- *Build
- run:
name: NPM Auth
command: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc
- run:
name: Release
command: |
npx semantic-release && \
npx cross-ci :run \
npx commit-status success Version "'\${PROJECT_VERSION}'"
workflows:
version: 2
all:
jobs:
- test:
context: common-env
filters:
branches:
ignore:
- master
- gh-pages
master:
jobs:
- publish:
context: common-env
filters:
branches:
only: master
monthly:
triggers:
- schedule:
cron: '0 0 1 * *'
filters:
branches:
only: master
jobs:
- test:
context: common-env
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
root = true

[*]
indent_style = space
charset = utf-8
end_of_line = lf
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
27 changes: 27 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Logs
logs
*.log

# Runtime data
pids
*.pid
*.seed

# Coverage directory used by tools like istanbul
coverage

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
node_modules

# Users Environment Variables
.lock-wscript

# Babel build output
/lib

# Config files
environment.toml
.env
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"bracketSpacing": false,
"singleQuote": true,
"trailingComma": "all"
}
21 changes: 21 additions & 0 deletions LICENCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# The MIT License (MIT)

Copyright (c) 2019 [Forbes Lindesay](https://github.com/ForbesLindesay)

> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
> SOFTWARE.
64 changes: 64 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"name": "typescript-json-validator",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"bin": {
"typescript-json-validator": "./lib/cli.js"
},
"files": [
"lib/"
],
"repository": {
"type": "git",
"url": "https://github.com/ForbesLindesay/typescript-json-validator.git"
},
"scripts": {
"test": "jest --no-cache",
"test:coverage": "yarn test --coverage",
"test:watch": "yarn test --watch",
"clean": "rimraf lib && rimraf src/Example.validator.ts",
"prebuild": "yarn clean",
"build": "tsc",
"build:watch": "yarn build -w",
"postbuild": "node lib/usage && node lib/cli src/Example.ts ExampleType && rimraf lib/__tests__",
"precommit": "pretty-quick --staged",
"prepush": "yarn prettier:diff && yarn test",
"prettier": "prettier --ignore-path .gitignore --write './**/*.{js,jsx,ts,tsx}'",
"prettier:diff": "prettier --ignore-path .gitignore --list-different './**/*.{js,jsx,ts,tsx}'",
"ci:test": "yarn prettier:diff && yarn test"
},
"devDependencies": {
"@types/jest": "^23.1.5",
"@types/node": "^10.5.2",
"husky": "^0.14.3",
"jest": "^23.3.0",
"prettier": "^1.13.7",
"pretty-quick": "^1.6.0",
"rimraf": "^2.6.2",
"ts-jest": "^23.0.0",
"tslint": "^5.10.0",
"typescript": "^3.1.1"
},
"jest": {
"watchPathIgnorePatterns": [
"src/Example.validator.ts"
],
"moduleFileExtensions": [
"ts",
"js"
],
"testEnvironment": "node",
"transform": {
"^.+\\.ts$": "ts-jest"
},
"transformIgnorePatterns": [],
"testRegex": ".*/__tests__/.*\\.(test|spec)\\.ts$"
},
"dependencies": {
"@types/ajv": "^1.0.0",
"@types/cross-spawn": "^6.0.0",
"cross-spawn": "^6.0.5",
"typescript-json-schema": "^0.34.0",
"yargs": "^12.0.5"
}
}
11 changes: 11 additions & 0 deletions src/Example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export default interface ExampleType {
value: string;
/**
* @TJS-format email
*/
email?: string;
/**
* @default 42
*/
answer: number;
}
48 changes: 48 additions & 0 deletions src/Example.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// generated by typescript-json-validator

import Ajv = require('ajv');
import ExampleType from './Example';
import {inspect} from 'util';

const ajv = new Ajv({coerceTypes: false, allErrors: true, useDefaults: true});

export {ExampleType};
export const ExampleTypeSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
defaultProperties: [],
properties: {
answer: {
default: 42,
type: 'number',
},
email: {
format: 'email',
type: 'string',
},
value: {
type: 'string',
},
},
required: ['answer', 'value'],
type: 'object',
};

ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));

type ValidateFunction = ((data: any) => data is ExampleType) &
Pick<Ajv.ValidateFunction, 'errors'>;
const validateSchema = ajv.compile(ExampleTypeSchema) as ValidateFunction;

export default function validate(value: unknown): ExampleType {
if (validateSchema(value)) {
return value;
} else {
throw new Error(
(validateSchema.errors
? validateSchema.errors
.map(error => `ExampleType${error.dataPath} ${error.message}`)
.join('\n') + '\nExampleType value:\n\n'
: null || 'Error validating ExampleType:\n\n') + inspect(value),
);
}
}
54 changes: 54 additions & 0 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import run from '../';
let validate: any;

test('run', () => {
run(['src/Example.ts', 'ExampleType']);
validate = require('../Example.validator').default;
});

test('valid', () => {
expect(
validate({
value: 'Hello World',
}),
).toMatchInlineSnapshot(`
Object {
"answer": 42,
"value": "Hello World",
}
`);
expect(
validate({
value: 'Hello World',
email: '[email protected]',
}),
).toMatchInlineSnapshot(`
Object {
"answer": 42,
"email": "[email protected]",
"value": "Hello World",
}
`);
});

test('invalid', () => {
expect(() => validate({})).toThrowErrorMatchingInlineSnapshot(`
"ExampleType should have required property 'value'
ExampleType value:
{ answer: 42 }"
`);
expect(() =>
validate({
value: 'Hello World',
email: 'forbeslindesay.co.uk',
}),
).toThrowErrorMatchingInlineSnapshot(`
"ExampleType.email should match format \\"email\\"
ExampleType value:
{ value: 'Hello World',
email: 'forbeslindesay.co.uk',
answer: 42 }"
`);
});
5 changes: 5 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#! /usr/bin/env node

import run from './';

run();
Loading

0 comments on commit a8549f7

Please sign in to comment.