Skip to content

Commit

Permalink
feat: update typings
Browse files Browse the repository at this point in the history
  • Loading branch information
whxaxes committed Sep 10, 2018
1 parent 45cc2bf commit 55e276f
Show file tree
Hide file tree
Showing 21 changed files with 199 additions and 80 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ run/
*.log
dist/
.cache
test/fixtures/*/typings
test/fixtures/app*/typings
17 changes: 4 additions & 13 deletions src/generators/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,25 +72,16 @@ export default function(tsHelper: TsHelper) {
return { dist };
}

const { base, inserts, property } = config.interface;
const newType = `New${base}`;
const newConfigType = `New${config.interface}`;
return {
dist,
content:
`import { ${base} } from '${baseConfig.framework}';\n` +
`import { ${config.interface} } from '${baseConfig.framework}';\n` +
`${importList.join('\n')}\n` +
`${declarationList.join('\n')}\n` +
`type ${newType} = ${base} & ${moduleList.join(' & ')};\n\n` +
`declare module '${baseConfig.framework}' {\n` +
inserts
.map(prop => {
return (
` interface ${prop} {\n` +
` ${property}: ${newType};\n` +
` }\n`
);
})
.join('\n') +
` type ${newConfigType} = ${moduleList.join(' & ')};\n` +
` interface ${config.interface} extends ${newConfigType} { };\n` +
`}`,
};
});
Expand Down
69 changes: 35 additions & 34 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ declare global {
}
}

export interface WatchItem extends PlainObject {
export interface BaseWatchItem {
path: string;
generator: string;
enabled: boolean;
trigger?: string[];
pattern?: string;
}

export interface WatchItem extends PlainObject, BaseWatchItem { }

export interface TsHelperOption {
cwd?: string;
framework?: string;
Expand Down Expand Up @@ -51,6 +53,9 @@ export type TsGenerator<T, U = GeneratorResult | GeneratorResult[] | void> = (
baseConfig: TsHelperConfig,
) => U;

// partial and exclude some properties
type PartialExclude<T, K extends keyof T> = { [P in K]: T[P]; } & { [U in Exclude<keyof T, K>]?: T[U]; };

export const defaultConfig = {
cwd: process.cwd(),
framework: 'egg',
Expand All @@ -65,12 +70,22 @@ export const defaultConfig = {
configFile: './tshelper.js',
};

export function formatWatchItem(watchItem: WatchItem) {
return {
trigger: ['add', 'unlink'],
generator: 'class',
enabled: true,
...watchItem,
};
}

// default watch dir
export function getDefaultWatchDirs(opt?: TsHelperOption) {
const baseConfig: { [key: string]: PartialExclude<BaseWatchItem, 'path'> & PlainObject } = {};
const watchConfig: { [key: string]: WatchItem | boolean } = {};

// extend
watchConfig.extend = {
baseConfig.extend = {
path: 'app/extend',
interface: {
context: 'Context',
Expand All @@ -81,86 +96,74 @@ export function getDefaultWatchDirs(opt?: TsHelperOption) {
helper: 'IHelper',
},
generator: 'extend',
trigger: ['add', 'change', 'unlink'],
enabled: true,
};

// controller
watchConfig.controller = {
baseConfig.controller = {
path: 'app/controller',
interface: 'IController',
generator: 'class',
trigger: ['add', 'unlink'],
enabled: true,
};

// middleware
watchConfig.middleware = {
baseConfig.middleware = {
path: 'app/middleware',
interface: 'IMiddleware',
interfaceHandle: val => `typeof ${val}`,
generator: 'class',
trigger: ['add', 'unlink'],
enabled: true,
};

// proxy
watchConfig.proxy = {
baseConfig.proxy = {
path: 'app/proxy',
interface: 'IProxy',
generator: 'class',
trigger: ['add', 'unlink'],
enabled: false,
};

// model
watchConfig.model = {
baseConfig.model = {
path: 'app/model',
generator: 'class',
interface: 'IModel',
caseStyle: 'upper',
interfaceHandle: val => `ReturnType<typeof ${val}>`,
trigger: ['add', 'unlink'],
enabled: true,
};

if (utils.moduleExist('egg-sequelize', (opt || {}).cwd)) {
watchConfig.model.interface = 'Sequelize';
watchConfig.model.framework = 'sequelize';
if (opt && utils.moduleExist('egg-sequelize', opt.cwd)) {
baseConfig.model.interface = 'Sequelize';
baseConfig.model.framework = 'sequelize';
}

// config
watchConfig.config = {
baseConfig.config = {
path: 'config',
pattern: 'config*.(ts|js)',
interface: {
inserts: ['Application', 'Controller', 'Service'],
property: 'config',
base: 'EggAppConfig',
},
interface: 'EggAppConfig',
generator: 'config',
trigger: ['add', 'unlink', 'change'],
enabled: true,
};

// plugin
watchConfig.plugin = {
baseConfig.plugin = {
path: 'config',
pattern: 'plugin*.(ts|js)',
generator: 'plugin',
trigger: ['add', 'unlink', 'change'],
enabled: true,
};

// service
watchConfig.service = {
baseConfig.service = {
path: 'app/service',
interface: 'IService',
generator: 'class',
trigger: ['add', 'unlink'],
enabled: true,
};

// format config
Object.keys(baseConfig).forEach(k => {
watchConfig[k] = formatWatchItem(baseConfig[k] as WatchItem);
});

return watchConfig;
}

Expand All @@ -169,9 +172,7 @@ const gd = path.resolve(__dirname, './generators');
const generators = fs
.readdirSync(gd)
.filter(f => !f.endsWith('.d.ts'))
.map(
f => require(path.resolve(gd, f.substring(0, f.lastIndexOf('.')))).default,
);
.map(f => require(path.resolve(gd, f.substring(0, f.lastIndexOf('.')))).default);

export default class TsHelper extends EventEmitter {
readonly config: TsHelperConfig;
Expand Down Expand Up @@ -419,7 +420,7 @@ function mergeConfig(base: TsHelperConfig, ...args: TsHelperOption[]) {
if (base.watchDirs[k]) {
Object.assign(base.watchDirs[k], item);
} else {
base.watchDirs[k] = item;
base.watchDirs[k] = formatWatchItem(item);
}
}
});
Expand Down
32 changes: 10 additions & 22 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,22 @@ export function loadFiles(cwd: string, pattern?: string) {

return fileList.filter(f => {
// filter same name js/ts
return !(
f.endsWith('.js') &&
fileList.includes(f.substring(0, f.length - 2) + 'ts')
);
return !(f.endsWith('.js') && fileList.includes(f.substring(0, f.length - 2) + 'ts'));
});
}

// clean same name js/ts
export function cleanJs(cwd: string) {
const fileList: string[] = [];
glob
.sync(['**/*.ts', '!**/*.d.ts', '!**/node_modules'], { cwd })
.forEach(f => {
const jf = removeSameNameJs(path.resolve(cwd, f));
if (jf) {
fileList.push(jf);
}
});
glob.sync(['**/*.ts', '!**/*.d.ts', '!**/node_modules'], { cwd }).forEach(f => {
const jf = removeSameNameJs(path.resolve(cwd, f));
if (jf) {
fileList.push(jf);
}
});

if (fileList.length) {
console.info(
`[egg-ts-helper] These file was deleted because the same name ts file was exist!\n`,
);
console.info(`[egg-ts-helper] These file was deleted because the same name ts file was exist!\n`);
console.info(' ' + fileList.join('\n ') + '\n');
}
}
Expand All @@ -43,9 +36,7 @@ export function getModuleObjByPath(f: string) {
const props = f.split('/').map(formatProp);

// composing moduleName
const moduleName = props
.map(prop => camelProp(prop, 'upper'))
.join('');
const moduleName = props.map(prop => camelProp(prop, 'upper')).join('');

return {
props,
Expand Down Expand Up @@ -91,10 +82,7 @@ export function isModuleExports(node: ts.Node) {
const obj = node.expression;
const prop = node.name;
return (
ts.isIdentifier(obj) &&
obj.escapedText === 'module' &&
ts.isIdentifier(prop) &&
prop.escapedText === 'exports'
ts.isIdentifier(obj) && obj.escapedText === 'module' && ts.isIdentifier(prop) && prop.escapedText === 'exports'
);
}

Expand Down
1 change: 1 addition & 0 deletions test/fixtures/app/config/config.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export default appInfo => {

return config;
};

15 changes: 12 additions & 3 deletions test/fixtures/app/config/config.local.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
export default {
middleware: [
export const view = '123';

export default appInfo => {
const config: any = {};

// should change to your own
config.keys = appInfo.name + '_1513135333623_4128';

config.middleware = [
'uuid',
],
];

return config;
};
1 change: 1 addition & 0 deletions test/fixtures/real/app/controller/home.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export default class HomeController extends Controller {
ctx.response.customLog();
ctx.helper.customLog();
app.customPluginLog();
console.info(app.config.otherBizConfig.type);
console.info(await ctx.service.db.fetch());
console.info(await app.model.User.get());
console.info('biz config', ctx.app.config.biz.type);
Expand Down
14 changes: 14 additions & 0 deletions test/fixtures/real/config/config.local.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { EggAppConfig, PowerPartial } from 'egg';

export default function() {
// built-in config
const config: PowerPartial<EggAppConfig> = {};

config.keys = '123123';

config.biz = {
type: 'local',
};

return config;
}
7 changes: 7 additions & 0 deletions test/fixtures/real/config/config.prod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function() {
return {
otherBizConfig: {
type: 'value',
},
};
}
11 changes: 11 additions & 0 deletions test/fixtures/real/typings/app/controller/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// This file was auto created by egg-ts-helper
// Do not modify this file!!!!!!!!!

import 'egg'; // Make sure ts to import egg declaration at first
import Home from '../../../app/controller/home';

declare module 'egg' {
interface IController {
home: Home;
}
}
9 changes: 9 additions & 0 deletions test/fixtures/real/typings/app/extend/application.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file was auto created by egg-ts-helper
// Do not modify this file!!!!!!!!!

import 'egg'; // Make sure ts to import egg declaration at first
import ExtendApplication from '../../../app/extend/application';
declare module 'egg' {
type ExtendApplicationType = typeof ExtendApplication;
interface Application extends ExtendApplicationType { }
}
9 changes: 9 additions & 0 deletions test/fixtures/real/typings/app/extend/context.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file was auto created by egg-ts-helper
// Do not modify this file!!!!!!!!!

import 'egg'; // Make sure ts to import egg declaration at first
import ExtendContext from '../../../app/extend/context';
declare module 'egg' {
type ExtendContextType = typeof ExtendContext;
interface Context extends ExtendContextType { }
}
9 changes: 9 additions & 0 deletions test/fixtures/real/typings/app/extend/helper.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file was auto created by egg-ts-helper
// Do not modify this file!!!!!!!!!

import 'egg'; // Make sure ts to import egg declaration at first
import ExtendIHelper from '../../../app/extend/helper';
declare module 'egg' {
type ExtendIHelperType = typeof ExtendIHelper;
interface IHelper extends ExtendIHelperType { }
}
9 changes: 9 additions & 0 deletions test/fixtures/real/typings/app/extend/request.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file was auto created by egg-ts-helper
// Do not modify this file!!!!!!!!!

import 'egg'; // Make sure ts to import egg declaration at first
import ExtendRequest from '../../../app/extend/request';
declare module 'egg' {
type ExtendRequestType = typeof ExtendRequest;
interface Request extends ExtendRequestType { }
}
9 changes: 9 additions & 0 deletions test/fixtures/real/typings/app/extend/response.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file was auto created by egg-ts-helper
// Do not modify this file!!!!!!!!!

import 'egg'; // Make sure ts to import egg declaration at first
import ExtendResponse from '../../../app/extend/response';
declare module 'egg' {
type ExtendResponseType = typeof ExtendResponse;
interface Response extends ExtendResponseType { }
}

0 comments on commit 55e276f

Please sign in to comment.