Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor/rest #1

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
{
"name": "typescriptest",
"version": "1.0.1",
"version": "1.0.3",
"description": "some typescript build exp",
"main": "dist/index.js",
"bin": {
"stool": "dist/bin/tool.js"
"stool": "dist/bin/tool.js",
"restrun": "dist/bin/restrun.js"
},
"directories": {
"typings": "typings.d.ts",
"typescript": {
"definition": "Somelib.d.ts"
},
"directories": {},
"dependencies": {
"chai": "^3.5.0",
"typescript": "^1.8.10",
"cookies": "0.6.1",
"koa": "^2.0.0",
"oauth2-server": "^2.4.1",
"ts-router": "^0.2.6",
"typescript": "^2.0.3",
"typescript-require": "^0.2.9-1",
"typings-core": "^1.4.0"
"typings-core": "^1.5.0"
},
"devDependencies": {
"mocha": "^3.0.1"
},
"scripts": {
"start": "ts-node src/bin/restrun.ts",
"test": "tsc && mocha dist/test"
},
"keywords": [
Expand Down
75 changes: 75 additions & 0 deletions src/bin/restrun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import * as tsRouter from 'ts-router';
import * as Koa from 'koa';
import * as mem from '../lib/oauth2';
let oauthServer = require('oauth2-server');
const app = new Koa();
const oamodel = new mem.InMemoryCache();
const router = new tsRouter. Router();


class User{
name :string
password :string

constructor(name:string,password:string) {
this.name = name
this.password = password
}
}
@tsRouter.Path('/:version')
class TestController extends tsRouter.Controller {
@tsRouter.PathParam('v1') private v1:string;
private v2:string;
constructor() {
super();
this.v1 = this.v1 + this.v1;
}

@tsRouter.Path('/grant')
@tsRouter.POST
@tsRouter.Consume(tsRouter.MediaType.JSON)
@tsRouter.Produce(tsRouter.MediaType.JSON)
async grant(@tsRouter.Body body:Object):Promise<tsRouter.Response> {
return tsRouter.Response.status(200).body({body}).build();
}

@tsRouter.Path('/:v1/:v2')
@tsRouter.GET
@tsRouter.Produce(tsRouter.MediaType.JSON)
async index(@tsRouter.Params params:Object):Promise<tsRouter.Response> {
let v1 = this.v1;
let v2 = this.v2;
return tsRouter.Response.status(200).body({v1, v2, params}).build();
}

@tsRouter.Before


async before(@tsRouter.PathParam('version') v2:string,@tsRouter.AppContext context:tsRouter.Context) {
this.v2 = v2;
}


}

router.use(TestController);
let oauth = oauthServer({
model: oamodel,
grants: ['password'],
debug: true
});



app.use(router.routes());

/*
app.use(oauth.authorise())
app.use( async (ctx, next) => {
this.body = "hello"
await next();
});
*/
app.listen(3000);

console.log('started at http://localhost:3000');
8 changes: 6 additions & 2 deletions src/bin/tool.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env node
/// <reference path="../../typings/modules/typings-core/index.d.ts" />
import { Emitter } from 'typings-core'
interface Argv {
help: boolean
Expand All @@ -21,4 +21,8 @@ interface Args extends Argv {
_: string[]
emitter: Emitter
}
console.log("some tool")
/*
*
*/
let s = 3
console.log("some tool"+s)
26 changes: 15 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import fs = require("fs");
declare module example {
interface IGreeterService {
greet(name: string):string;
}
}
import * as fst from "./lib/reflect";
//import fs = require("fs");
export interface IGreeterService {
greet(name: string):string
}

export default class Greeter implements example.IGreeterService {
greeting: string;
export class Greeter implements IGreeterService {
@fst.format("Hello:%s")
greeting: string
constructor(message: string) {
this.greeting = message;
this.greeting = message
}
greet(){
let formatString = fst.getFormat(this, "greeting");
return formatString.replace("%s", this.greeting);
}
greet(name: string): string {
return this.greeting + " " + name;
greetbyname(name: string): string {
return this.greeting + ":" + name
}
}

86 changes: 86 additions & 0 deletions src/lib/oauth2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@

export class InMemoryCache {
clients :{ [key:string] : any}[]
tokens:{ [key:string] : string}[]
users:{ [key:string] : string}[]
constructor(){
this.clients = [{ clientId : 'thom', clientSecret : 'nightworld', 'redirectUris' : [''] }];
this.tokens = [];
this.users = [{ id : '123', username: 'thomseddon', password: 'nightworld' }];
}

/**
* Dump the cache.
*/

dump() {
console.log('clients', this.clients);
console.log('tokens', this.tokens);
console.log('users', this.users);
};

/*
* Get access token.
*/

async getAccessToken (bearerToken:string) {
var tokens = this.tokens.filter(function(token) {
return token [ 'accessToken' ] === bearerToken;
});

return tokens.length ? tokens[0] : false;
};


/**
* Get refresh token.
*/

async getRefreshToken(bearerToken:string) {
let tokens = this.tokens.filter(function(token) {
return token [ 'refreshToken' ] === bearerToken;
});

return tokens.length ? tokens[0] : false;
};


/**
* Get client.
*/

async getClient(clientId:string, clientSecret:string) {
let clients = this.clients.filter(function(client) {
return client [ 'clientId' ] === clientId && client [ 'clientSecret' ] === clientSecret;
});

return clients.length ? clients[0] : false;
};

/**
* Save token.
*/

async saveToken (token:any, client:any, user:any) {
this.tokens.push({
accessToken: token['accessToken'],
accessTokenExpiresAt: token['accessTokenExpiresAt'],
clientId: client['clientId'],
refreshToken: token [ 'refreshToken' ],
refreshTokenExpiresAt: token [ 'refreshTokenExpiresAt' ],
userId: user [ 'id' ]
});
};

/*
* Get user.
*/

async getUser (username:string, password:string) {
let users = this.users.filter(function(user) {
return user['username'] === username && user [ 'password' ] === password;
});

return users.length ? users[0] : false;
};
}
14 changes: 14 additions & 0 deletions src/lib/reflect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import "reflect-metadata";

const formatMetadataKey = Symbol("format");

export function format(formatString: string) {
return Reflect.metadata(formatMetadataKey, formatString);
}

export function getFormat(target: any, propertyKey: string) {
return Reflect.getMetadata(formatMetadataKey, target, propertyKey);
}



17 changes: 7 additions & 10 deletions src/test/codeTest.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@

import Greeter from "../index";
import chai = require('chai');
import * as fst from "../index";
import * as chai from 'chai';

/**
* Globals
Expand All @@ -27,14 +26,12 @@ describe('User Model Unit Tests:', () => {
});

describe('Greeter-test', function () {
var subject : Greeter;

let subject : fst.Greeter;
beforeEach(function () {
subject = new Greeter("Hello");
subject = new fst.Greeter("wooz");
});
it('should execute', function () {
var ret = subject.greet("wooz");

expect(ret).to.equals("Hello wooz");
it('greet string should equals', function () {
let ret = subject.greet();
expect(ret).to.equals("Hello:wooz");
})
})
33 changes: 18 additions & 15 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
{
"filesGlob" :[
"src/**/*.ts"
] ,
"filesGlob": [
"src/**/*.ts"
],
"files": [
"typings/index.d.ts"
,"src/index.ts"
"src/index.ts"
, "src/bin/tool.ts"
, "src/bin/restrun.ts"
, "src/lib/oauth2.ts"
, "src/test/codeTest.ts"
],

"compileOnSave": false,
"compilerOptions": {
"outDir": "dist/",
"moduleResolution": "node",
"noImplicitAny": true,
"target": "es5"
,"sourceMap": true
,"module": "commonjs"
,"newLine": "LF"
}
,"exclude": [
"node_modules"
]

"target": "es6",
"sourceMap": false,
"module": "commonjs",
"newLine": "LF"
,"experimentalDecorators": true
,"emitDecoratorMetadata":true
},
"exclude": [
"node_modules"
]
}
13 changes: 10 additions & 3 deletions typings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
{
"dependencies": {
"chai": "registry:npm/chai#3.5.0+20160723033700"
,"typings-core": "npm:typings-core"
"chai": "registry:npm/chai#3.5.0+20160723033700",
"typings-core": "npm:typings-core"
},
"globalDependencies": {
"cookies": "registry:dt/cookies#0.5.1+20160316171810",
"express": "registry:dt/express#4.0.0+20160708185218",
"express-serve-static-core": "registry:dt/express-serve-static-core#4.0.0+20160923124352",
"koa": "registry:dt/koa#2.0.0+20160724024233",
"mime": "registry:dt/mime#0.0.0+20160316155526",
"mocha": "registry:dt/mocha#2.2.5+20160720003353",
"node": "github:DefinitelyTyped/DefinitelyTyped/node/node.d.ts#48c1e3c1d6baefa4f1a126f188c27c4fefd36bff"
"node": "registry:dt/node#6.0.0+20160923124626",
"oauth2-server": "registry:dt/oauth2-server#0.0.0+20160317120654",
"serve-static": "registry:dt/serve-static#0.0.0+20160606155157"
}
}