type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
MethodDeclaration |
_getContextFont() {
return Text.prototype._getContextFont.call(this);
} | phucdo1711/konva | src/shapes/TextPath.ts | TypeScript |
MethodDeclaration |
_getTextSize(text) {
var dummyCanvas = this.dummyCanvas;
var _context = dummyCanvas.getContext('2d');
_context.save();
_context.font = this._getContextFont();
var metrics = _context.measureText(text);
_context.restore();
return {
width: metrics.width,
height: parseInt(this.attrs.fontSize, 10),
};
} | phucdo1711/konva | src/shapes/TextPath.ts | TypeScript |
MethodDeclaration |
getSelfRect() {
if (!this.glyphInfo.length) {
return {
x: 0,
y: 0,
width: 0,
height: 0,
};
}
var points = [];
this.glyphInfo.forEach(function (info) {
points.push(info.p0.x);
points.push(info.p0.y);
points.push(info.p1.x);
points.push(info.p1.y);
});
var minX = points[0] || 0;
var maxX = points[0] || 0;
var minY = points[1] || 0;
var maxY = points[1] || 0;
var x, y;
for (var i = 0; i < points.length / 2; i++) {
x = points[i * 2];
y = points[i * 2 + 1];
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
var fontSize = this.fontSize();
return {
x: minX - fontSize / 2,
y: minY - fontSize / 2,
width: maxX - minX + fontSize,
height: maxY - minY + fontSize,
};
} | phucdo1711/konva | src/shapes/TextPath.ts | TypeScript |
TypeAliasDeclaration |
export type ListServicesExceptionsUnion =
| AccessDeniedException
| IllegalArgumentException
| InvalidPaginationTokenException
| ServiceException
| TooManyRequestsException; | Dylan0916/aws-sdk-js-v3 | clients/browser/client-service-quotas-browser/types/ListServicesExceptionsUnion.ts | TypeScript |
FunctionDeclaration |
export function Main() {
const [text, setText] = useState('');
const [searchWords, setSearchWords] = useState<string[]>([]);
const [categories, setCategories] = useState<Record<string, string>>({});
const [highlightedText, setHighlightedText] = useState<string>('');
const [wordsByCategory, setWordsByCategory] = useState<Record<string, string[]>>({});
const [statistics, setStatistics] = useState<Record<string, number>>({})
const onClick = () => {
const response = fetch('/rpc/', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
"jsonrpc": "2.0",
"method": "process_input_text",
"params": {"text": text},
"id": 1
})
})
.then(response => response.json())
.then(response => {
const arrWords = []
const arrCategories: Record<string, string> = {}
for (const element of response.result) {
for (const el of element.analysis) {
const category = el.categories
const word = el.word
arrWords.push(word)
arrCategories[word] = category.join('')
for (const cat of category) {
if (!wordsByCategory[cat]) wordsByCategory[cat] = [];
wordsByCategory[cat].push(word);
}
const loanword_ratio = element.statistics.loanword_ratio
const expressive_ratio = element.statistics.expressive_ratio
const obscene_ratio = element.statistics.obscene_ratio
statistics['loanword_ratio'] = loanword_ratio
statistics['expressive_ratio'] = expressive_ratio
statistics['obscene_ratio'] = obscene_ratio
}
}
setSearchWords(arrWords);
setHighlightedText(text);
setCategories(arrCategories);
setWordsByCategory(wordsByCategory);
setStatistics(statistics);
}
);
}
const onChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
setText(event.target.value);
}
const legend = [
'заимствование',
'обсценная лексика',
'экспрессивная лексика',
'обсценное заимствование',
'экспрессивная заимствованная лексика',
'обсценная экспрессивная лексика'
];
const colorMap: any = {
'заимствование': 'cornflowerblue',
'обсценная лексика': 'indianred',
'экспрессивная лексика': 'yellow',
'обсценное заимствование': 'violet',
'экспрессивная заимствованная лексика': 'green',
'обсценная экспрессивная лексика': 'orange'
};
const categoriesMap: any = {
'loanword': 'Заимствования: \n',
'expressive': 'Экспрессивная лексика: \n',
'obscene': 'Обсценная лексика: \n',
};
const statisticsMap: any = {
'loanword_ratio': 'Коэффициент заимствований: \n',
'expressive_ratio': 'Коэффициент экспрессивной лексики: \n',
'obscene_ratio': 'Коэффициент обсценной лексики: \n',
}
return (
<Layout className="text-input-output">
<Space direction="vertical" size={"middle"}>
<div className="about-on-main">
<p>Мы рады приветствовать вас на официальном сайте проекта Antidict. Наш проект посвящён
автоматическому
распознаванию англоязычных заимствований, экспрессивных форм и намеренных искажений (эрративов)
в
тексте. В основе нашего механизма лежит многоклассовый классификатор, изначально обученный для
определения этих типов слов на корпусе ГИКРЯ. Для обучения распознаванию англоязычных
заимствований
наш классификатор был обучен на словаре Дьякова. Для классификации эрративов и экспрессивных
слов
нами были собраны отдельные датасеты, на которых классификатор обучался. Эрративы
рассматриваются
нами как подкласс слов с экспрессивной окраской, которые также включают в себя слова с
экспрессивными аффиксами и мат.</p>
<p>Проект представлен студентами магистратуры школы лингвистики Национального исследовательского
университета "Высшая школа экономики". Разработка проекта проходила в 2019-2020 годах. В данный
момент над совершенствованием Antidict трудятся 5 человек: Антон Вахранёв, Алексей Доркин, Ирина
Дьячкова, Лидия Остякова и Владислава Смирнова. Надеемся, наш проект будет полезен для вас!</p>
</div>
<Content className="text-input" style={{textAlign: 'center'}} | lapythie/hseling-repo-antidict | hseling-web-antidict/src/pages/main.tsx | TypeScript |
ArrowFunction |
() => {
const response = fetch('/rpc/', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({
"jsonrpc": "2.0",
"method": "process_input_text",
"params": {"text": text},
"id": 1
})
})
.then(response => response.json())
.then(response => {
const arrWords = []
const arrCategories: Record<string, string> = {}
for (const element of response.result) {
for (const el of element.analysis) {
const category = el.categories
const word = el.word
arrWords.push(word)
arrCategories[word] = category.join('')
for (const cat of category) {
if (!wordsByCategory[cat]) wordsByCategory[cat] = [];
wordsByCategory[cat].push(word);
}
const loanword_ratio = element.statistics.loanword_ratio
const expressive_ratio = element.statistics.expressive_ratio
const obscene_ratio = element.statistics.obscene_ratio
statistics['loanword_ratio'] = loanword_ratio
statistics['expressive_ratio'] = expressive_ratio
statistics['obscene_ratio'] = obscene_ratio
}
}
setSearchWords(arrWords);
setHighlightedText(text);
setCategories(arrCategories);
setWordsByCategory(wordsByCategory);
setStatistics(statistics);
}
);
} | lapythie/hseling-repo-antidict | hseling-web-antidict/src/pages/main.tsx | TypeScript |
ArrowFunction |
response => {
const arrWords = []
const arrCategories: Record<string, string> = {}
for (const element of response.result) {
for (const el of element.analysis) {
const category = el.categories
const word = el.word
arrWords.push(word)
arrCategories[word] = category.join('')
for (const cat of category) {
if (!wordsByCategory[cat]) wordsByCategory[cat] = [];
wordsByCategory[cat].push(word);
}
const loanword_ratio = element.statistics.loanword_ratio
const expressive_ratio = element.statistics.expressive_ratio
const obscene_ratio = element.statistics.obscene_ratio
statistics['loanword_ratio'] = loanword_ratio
statistics['expressive_ratio'] = expressive_ratio
statistics['obscene_ratio'] = obscene_ratio
}
}
setSearchWords(arrWords);
setHighlightedText(text);
setCategories(arrCategories);
setWordsByCategory(wordsByCategory);
setStatistics(statistics);
} | lapythie/hseling-repo-antidict | hseling-web-antidict/src/pages/main.tsx | TypeScript |
ArrowFunction |
(event: ChangeEvent<HTMLTextAreaElement>) => {
setText(event.target.value);
} | lapythie/hseling-repo-antidict | hseling-web-antidict/src/pages/main.tsx | TypeScript |
ArrowFunction |
({
item,
checkboxUpdate,
editDeleteOnClick,
}: {
item: ListItem;
checkboxUpdate: CheckboxUpdateHandler;
editDeleteOnClick: EditDeleteOnClickHandler;
}) => (
<li>
<div className="d-flex ListItem">
<div className | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
ArrowFunction |
({
items,
checkboxUpdate,
editDeleteOnClick,
}: {
items: ListItem[];
checkboxUpdate: CheckboxUpdateHandler;
editDeleteOnClick: EditDeleteOnClickHandler;
}) => {
return (
<ul>
{items.map((item, index) => (
<SortableListItem
key={`list-item-${index}`}
index={index}
item={item}
checkboxUpdate={checkboxUpdate}
editDeleteOnClick={editDeleteOnClick}
/> | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
ArrowFunction |
(item, index) => (
<SortableListItem
key={`list-item-${index}` | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
ArrowFunction |
() => this.getListInfo() | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
ClassDeclaration |
export default class List extends React.Component<any, ListState> {
private refreshTimeout: NodeJS.Timeout;
constructor(props: any) {
super(props);
this.state = {
refreshClicked: false,
newItemFormGood: false,
newItemSubmitClicked: false,
editNameFormGood: true,
editNameSubmitClicked: false,
deleteListClicked: false,
editItemFormGood: true,
editItemSubmitClicked: false,
editingItemID: "",
deleteListItemClicked: false,
listInfo: null,
};
this.refreshTimeout = setTimeout(() => {}, 0);
}
public componentWillMount() {
if (getCookie("loggedIn") !== "true") {
this.props.history.push(
`/login?after=/list/${this.props.match.params.listID}`
);
}
}
public componentDidMount() {
this.getListInfo();
}
public render() {
if (this.state.listInfo === null) {
return (
<div className="List">
<h1 className="mb-3">List</h1>
<p className="loading">Fetching list data...</p>
</div>
);
} else {
return (
<div className="List">
<h1 className="mb-3">
<ReactMarkdown
plugins={[gfm]}
children={this.state.listInfo.title}
linkTarget="_blank"
/>
</h1>
<div className="ListItems">
<ul>
<li>
<div className="List-Buttons">
<div>
<button
type="button"
className="btn btn-pink btn-icon"
onClick={() => this.props.history.push("/")}
aria-label="Back"
>
<i className="fas fa-chevron-left" />
</button>
</div>
<div>
<button
type="button"
className="btn btn-pink btn-icon"
onClick={() => this.getListInfo()}
disabled={this.state.refreshClicked}
aria | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
InterfaceDeclaration |
interface ListItem {
listItemID: string;
content: string;
position: number;
checked: boolean;
} | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
InterfaceDeclaration |
interface ListInfo {
title: string;
items: ListItem[];
} | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
InterfaceDeclaration |
interface ListState {
refreshClicked: boolean;
newItemFormGood: boolean;
newItemSubmitClicked: boolean;
editNameFormGood: boolean;
editNameSubmitClicked: boolean;
deleteListClicked: boolean;
editItemFormGood: boolean;
editItemSubmitClicked: boolean;
editingItemID: string;
deleteListItemClicked: boolean;
listInfo: ListInfo | null;
} | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
TypeAliasDeclaration |
type CheckboxUpdateHandler = (listItemID: string) => void; | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
TypeAliasDeclaration |
type EditDeleteOnClickHandler = (listItemID: string) => void; | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
public componentWillMount() {
if (getCookie("loggedIn") !== "true") {
this.props.history.push(
`/login?after=/list/${this.props.match.params.listID}`
);
}
} | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
public componentDidMount() {
this.getListInfo();
} | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
public render() {
if (this.state.listInfo === null) {
return (
<div className="List">
<h1 className="mb-3">List</h1>
<p className="loading">Fetching list data...</p>
</div>
);
} else {
return (
<div className="List">
<h1 className="mb-3">
<ReactMarkdown
plugins={[gfm]}
children={this.state.listInfo.title}
linkTarget="_blank"
/>
</h1>
<div className="ListItems">
<ul>
<li>
<div className="List-Buttons">
<div>
<button
type="button"
className="btn btn-pink btn-icon"
onClick={() => this.props.history.push("/")}
aria-label="Back"
>
<i className="fas fa-chevron-left" />
</button>
</div>
<div>
<button
type="button"
className="btn btn-pink btn-icon"
onClick={() => this.getListInfo()} | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
clearTimeout(this | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
if (res | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
if (res1 | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
if (event | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
MethodDeclaration |
setTimeout( | WKHAllen/Notenheim | app/src/components/List.tsx | TypeScript |
ArrowFunction |
(): CTX => {
const context = CTXContext.use().value;
if (!context) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions
throw new Error(`Expected modern context, but got: ${context}`);
}
return context;
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
ArrowFunction |
(): Config => {
const config = ConfigContext.use().value;
if (!config) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions
throw new Error(`Expected modern config, but got: ${config}`);
}
return config;
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
ArrowFunction |
(): WebpackConfig => {
const webpackConfig = WebpackConfigContext.use().value;
if (!webpackConfig) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions
throw new Error(`Expected webpack config, but got: ${webpackConfig}`);
}
return webpackConfig;
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
ArrowFunction |
(): BabelConfig => {
const babelConfig = BabelConfigContext.use().value;
if (!babelConfig) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions
throw new Error(`Expected babel config, but got: ${babelConfig}`);
}
return babelConfig;
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
ArrowFunction |
async (context: CTX) => {
const runner = await main.init();
main.run(() => {
CTXContext.set(context);
});
runner.prepare();
// eslint-disable-next-line @typescript-eslint/no-shadow
const { config, webpackConfig, babelConfig } = runner.config({
config: defaultConfig,
webpackConfig: defaultWebpackConfig,
babelConfig: defaultBabelConfig,
});
main.run(() => {
ConfigContext.set(config);
WebpackConfigContext.set(webpackConfig);
BabelConfigContext.set(babelConfig);
});
runner.preDev();
runner.postDev();
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
ArrowFunction |
() => {
CTXContext.set(context);
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
ArrowFunction |
() => {
ConfigContext.set(config);
WebpackConfigContext.set(webpackConfig);
BabelConfigContext.set(babelConfig);
} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
InterfaceDeclaration | // eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ExternalProgress {} | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
TypeAliasDeclaration | // eslint-disable-next-line @typescript-eslint/ban-types
export type CTX = {}; | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
TypeAliasDeclaration | // eslint-disable-next-line @typescript-eslint/ban-types
export type Config = {}; | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
TypeAliasDeclaration | // eslint-disable-next-line @typescript-eslint/ban-types
export type WebpackConfig = {}; | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
TypeAliasDeclaration | // eslint-disable-next-line @typescript-eslint/ban-types
export type BabelConfig = {}; | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
TypeAliasDeclaration |
export type TestAsyncHooks = ExternalProgress & typeof lifecircle; | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
TypeAliasDeclaration |
export type TestAsyncPlugin = PluginOptions<
TestAsyncHooks,
AsyncSetup<TestAsyncHooks>
>; | huxuezhi/modern.js | packages/toolkit/plugin/tests/fixtures/async/core/index.ts | TypeScript |
FunctionDeclaration |
export function MessageHeader({
tag = "div",
...props
}: MessageHeader<HTMLElement>) {
const className = classNames("message-header", props.className);
return React.createElement(tag, {...props, className});
} | paolobueno/bloomer | src/components/Message/MessageHeader.tsx | TypeScript |
InterfaceDeclaration |
export interface MessageHeader<T> extends Bulma.Tag, React.HTMLProps<T> {} | paolobueno/bloomer | src/components/Message/MessageHeader.tsx | TypeScript |
ArrowFunction |
() => {
let fixture: ComponentFixture<DataTableHeaderCellComponent>;
let component: DataTableHeaderCellComponent;
let element: any;
// provide our implementations or mocks to the dependency injector
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [DataTableHeaderCellComponent]
});
});
beforeEach(
waitForAsync(() => {
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(DataTableHeaderCellComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
});
})
);
describe('fixture', () => {
it('should have a component instance', () => {
expect(component).toBeTruthy();
});
});
} | 4SELLERS/ngx-datatable | projects/swimlane/ngx-datatable/src/lib/components/header/header-cell.component.spec.ts | TypeScript |
ArrowFunction |
() => {
TestBed.configureTestingModule({
declarations: [DataTableHeaderCellComponent]
});
} | 4SELLERS/ngx-datatable | projects/swimlane/ngx-datatable/src/lib/components/header/header-cell.component.spec.ts | TypeScript |
ArrowFunction |
() => {
TestBed.compileComponents().then(() => {
fixture = TestBed.createComponent(DataTableHeaderCellComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
});
} | 4SELLERS/ngx-datatable | projects/swimlane/ngx-datatable/src/lib/components/header/header-cell.component.spec.ts | TypeScript |
ArrowFunction |
() => {
fixture = TestBed.createComponent(DataTableHeaderCellComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
} | 4SELLERS/ngx-datatable | projects/swimlane/ngx-datatable/src/lib/components/header/header-cell.component.spec.ts | TypeScript |
ArrowFunction |
() => {
it('should have a component instance', () => {
expect(component).toBeTruthy();
});
} | 4SELLERS/ngx-datatable | projects/swimlane/ngx-datatable/src/lib/components/header/header-cell.component.spec.ts | TypeScript |
ArrowFunction |
(item: Log) =>
console.log(
bytes.hexDataSlice(item.topics[1], 12),
bytes.hexDataSlice(item.topics[2], 12),
parseInt(item.topics[3])
) | RusAlex/arbitrum-review | src/parse.ts | TypeScript |
TypeAliasDeclaration |
type Log = {
address: string;
topics: string[4];
}; | RusAlex/arbitrum-review | src/parse.ts | TypeScript |
TypeAliasDeclaration |
type Logs = [Log]; | RusAlex/arbitrum-review | src/parse.ts | TypeScript |
ArrowFunction |
(loginUser: LoginUserDto): Observable<UserEntity> =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.findByUsername(loginUser.username).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new UnauthorizedException("Username and Password don't match"),
),
),
map((user: User) => ({
user,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
passwordIsValid: this._securityService.checkPassword(
loginUser.password,
Buffer.from(user.password_hash),
),
})),
mergeMap((_: { user: User; passwordIsValid: Observable<boolean> }) =>
merge(
_.passwordIsValid.pipe(
filter((passwordIsValid: boolean) => !!passwordIsValid),
map(() => _.user),
),
_.passwordIsValid.pipe(
filter((passwordIsValid: boolean) => !passwordIsValid),
mergeMap(() =>
throwError(
() =>
new UnauthorizedException(
"Username and Password don't match",
),
),
),
),
),
),
mergeMap((user: User & { id: string }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.updateLastAccessTime(user.id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during login process',
),
),
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(e) =>
throwError(() => new UnprocessableEntityException(e.message)) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() => new UnprocessableEntityException(e.message) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) =>
!!user
? of(user)
: throwError(
() =>
new UnauthorizedException("Username and Password don't match"),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new UnauthorizedException("Username and Password don't match") | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) => ({
user,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
passwordIsValid: this._securityService.checkPassword(
loginUser.password,
Buffer.from(user.password_hash),
),
}) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(_: { user: User; passwordIsValid: Observable<boolean> }) =>
merge(
_.passwordIsValid.pipe(
filter((passwordIsValid: boolean) => !!passwordIsValid),
map(() => _.user),
),
_.passwordIsValid.pipe(
filter((passwordIsValid: boolean) => !passwordIsValid),
mergeMap(() =>
throwError(
() =>
new UnauthorizedException(
"Username and Password don't match",
),
),
),
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(passwordIsValid: boolean) => !!passwordIsValid | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() => _.user | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(passwordIsValid: boolean) => !passwordIsValid | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
throwError(
() =>
new UnauthorizedException(
"Username and Password don't match",
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new UnauthorizedException(
"Username and Password don't match",
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User & { id: string }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.updateLastAccessTime(user.id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during login process',
),
),
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(e) =>
throwError(() => new UnprocessableEntityException(e.message)) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during login process',
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new PreconditionFailedException(
'An error occurred during login process',
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) => delete user.password_hash | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) => new UserEntity(user) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: CreateUserDto): Observable<UserEntity> =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._securityService.hashPassword(user.password).pipe(
map((hashPassword: Buffer) => ({
username: user.username,
display_name: user.display_name,
password_hash: hashPassword,
})),
mergeMap(
(_: Omit<CreateUserDto, 'password'> & { password_hash: Buffer }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.save(_),
),
catchError((e) =>
e.code === 11000
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(hashPassword: Buffer) => ({
username: user.username,
display_name: user.display_name,
password_hash: hashPassword,
}) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(_: Omit<CreateUserDto, 'password'> & { password_hash: Buffer }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.save(_) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(e) =>
e.code === 11000
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new ConflictException(
`Username '${user.username}' already exists`,
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(id: string, user: PatchUserDto): Observable<UserEntity> =>
of(of(user)).pipe(
mergeMap((obs: Observable<PatchUserDto>) =>
merge(
obs.pipe(
filter(
(_: PatchUserDto) =>
typeof _ !== 'undefined' && Object.keys(_).length > 0,
),
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
mergeMap((_: PatchUserDto) => this._userDao.patch(id, _)),
catchError((e) =>
e.code === 11000 && !!user.username
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
`User with id "${id}" doesn't exist in the database`,
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
),
obs.pipe(
filter(
(_: PatchUserDto) =>
typeof _ === 'undefined' || Object.keys(_).length === 0,
),
mergeMap(() =>
throwError(
() =>
new BadRequestException(
'Payload should at least contains one of "username", "display_name" or "skip_authenticator_registration"',
),
),
),
),
),
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(obs: Observable<PatchUserDto>) =>
merge(
obs.pipe(
filter(
(_: PatchUserDto) =>
typeof _ !== 'undefined' && Object.keys(_).length > 0,
),
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
mergeMap((_: PatchUserDto) => this._userDao.patch(id, _)),
catchError((e) =>
e.code === 11000 && !!user.username
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
`User with id "${id}" doesn't exist in the database`,
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
),
obs.pipe(
filter(
(_: PatchUserDto) =>
typeof _ === 'undefined' || Object.keys(_).length === 0,
),
mergeMap(() =>
throwError(
() =>
new BadRequestException(
'Payload should at least contains one of "username", "display_name" or "skip_authenticator_registration"',
),
),
),
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(_: PatchUserDto) =>
typeof _ !== 'undefined' && Object.keys(_).length > 0 | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(_: PatchUserDto) => this._userDao.patch(id, _) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(e) =>
e.code === 11000 && !!user.username
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new ConflictException(
`Username '${user.username}' already exists`,
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
`User with id "${id}" doesn't exist in the database`,
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new PreconditionFailedException(
`User with id "${id}" doesn't exist in the database`,
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(_: PatchUserDto) =>
typeof _ === 'undefined' || Object.keys(_).length === 0 | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
throwError(
() =>
new BadRequestException(
'Payload should at least contains one of "username", "display_name" or "skip_authenticator_registration"',
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new BadRequestException(
'Payload should at least contains one of "username", "display_name" or "skip_authenticator_registration"',
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(id: string): Observable<UserEntity> =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.findById(id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new UnauthorizedException(
'User cannot use this authenticator to authenticate',
),
),
),
mergeMap((user: User & { id: string }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.updateLastAccessTime(user.id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during webauthn login process',
),
),
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) =>
!!user
? of(user)
: throwError(
() =>
new UnauthorizedException(
'User cannot use this authenticator to authenticate',
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new UnauthorizedException(
'User cannot use this authenticator to authenticate',
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User & { id: string }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.updateLastAccessTime(user.id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during webauthn login process',
),
),
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
(user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during webauthn login process',
),
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ArrowFunction |
() =>
new PreconditionFailedException(
'An error occurred during webauthn login process',
) | akanass/webauthn | src/user/user.service.ts | TypeScript |
ClassDeclaration |
@Injectable()
export class UserService {
/**
* Class constructor
*
* @param {UserDao} _userDao dependency injection of UserDao instance
* @param {SecurityService} _securityService dependency injection of SecurityService instance
*/
constructor(
private readonly _userDao: UserDao,
private readonly _securityService: SecurityService,
) {}
/**
* Function to login an user by username/password
*
* @param {LoginUserDto} loginUser couple username/password to login the user
*
* @return {Observable<UserEntity>} the entity representing the logged in user
*/
login = (loginUser: LoginUserDto): Observable<UserEntity> =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.findByUsername(loginUser.username).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new UnauthorizedException("Username and Password don't match"),
),
),
map((user: User) => ({
user,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
passwordIsValid: this._securityService.checkPassword(
loginUser.password,
Buffer.from(user.password_hash),
),
})),
mergeMap((_: { user: User; passwordIsValid: Observable<boolean> }) =>
merge(
_.passwordIsValid.pipe(
filter((passwordIsValid: boolean) => !!passwordIsValid),
map(() => _.user),
),
_.passwordIsValid.pipe(
filter((passwordIsValid: boolean) => !passwordIsValid),
mergeMap(() =>
throwError(
() =>
new UnauthorizedException(
"Username and Password don't match",
),
),
),
),
),
),
mergeMap((user: User & { id: string }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.updateLastAccessTime(user.id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during login process',
),
),
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
);
/**
* Function to create a new user in the database
*
* @param {CreateUserDto} user payload
*
* @return {Observable<UserEntity>} the entity representing the new user
*/
create = (user: CreateUserDto): Observable<UserEntity> =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._securityService.hashPassword(user.password).pipe(
map((hashPassword: Buffer) => ({
username: user.username,
display_name: user.display_name,
password_hash: hashPassword,
})),
mergeMap(
(_: Omit<CreateUserDto, 'password'> & { password_hash: Buffer }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.save(_),
),
catchError((e) =>
e.code === 11000
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
);
/**
* Function to patch an user in the database
*
* @param {string} id user unique identifier in the database
* @param {PatchUserDto} user payload
*
* @return {Observable<UserEntity>} the entity representing the patched user
*/
patch = (id: string, user: PatchUserDto): Observable<UserEntity> =>
of(of(user)).pipe(
mergeMap((obs: Observable<PatchUserDto>) =>
merge(
obs.pipe(
filter(
(_: PatchUserDto) =>
typeof _ !== 'undefined' && Object.keys(_).length > 0,
),
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
mergeMap((_: PatchUserDto) => this._userDao.patch(id, _)),
catchError((e) =>
e.code === 11000 && !!user.username
? throwError(
() =>
new ConflictException(
`Username '${user.username}' already exists`,
),
)
: throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
`User with id "${id}" doesn't exist in the database`,
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
),
obs.pipe(
filter(
(_: PatchUserDto) =>
typeof _ === 'undefined' || Object.keys(_).length === 0,
),
mergeMap(() =>
throwError(
() =>
new BadRequestException(
'Payload should at least contains one of "username", "display_name" or "skip_authenticator_registration"',
),
),
),
),
),
),
);
/**
* Function to login an user by webauthn
*
* @param {string} id unique identifier of the user
*
* @return {Observable<UserEntity>} the entity representing the logged in user
*/
webAuthnLogin = (id: string): Observable<UserEntity> =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.findById(id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new UnauthorizedException(
'User cannot use this authenticator to authenticate',
),
),
),
mergeMap((user: User & { id: string }) =>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._userDao.updateLastAccessTime(user.id).pipe(
catchError((e) =>
throwError(() => new UnprocessableEntityException(e.message)),
),
mergeMap((user: User) =>
!!user
? of(user)
: throwError(
() =>
new PreconditionFailedException(
'An error occurred during webauthn login process',
),
),
),
),
),
tap((user: User) => delete user.password_hash),
map((user: User) => new UserEntity(user)),
);
} | akanass/webauthn | src/user/user.service.ts | TypeScript |
FunctionDeclaration | /**
* Updates the column sizes of the columns provided based on the column definition metadata for each column.
* The final width represent a static width, it is the value as set in the definition (except column without width, where the calculated global width is set).
*/
export function resetColumnWidths(rowWidth: StaticColumnWidthLogic,
tableColumns: PblColumn[],
metaColumns: PblMetaColumnStore[]): void {
const { pct, px } = rowWidth.defaultColumnWidth;
const defaultWidth = `calc(${pct}% - ${px}px)`;
for (const c of tableColumns) {
c.setDefaultWidth(defaultWidth);
c.updateWidth();
}
for (const m of metaColumns) {
for (const c of [m.header, m.footer]) {
if (c) {
c.updateWidth('');
}
}
// We don't handle groups because they are handled by `PblNgridComponent.resizeRows()`
// which set the width for each.
}
} | Danieliverant/ngrid | libs/ngrid/src/lib/grid/utils/width.ts | TypeScript |
FunctionDeclaration |
async function getPage(config: CanvasConfig, link: string): Promise<CanvasStudent[]> {
return fetch(link, {
headers: {
Authorization: `Bearer ${config.token}`,
}
}).then(resp => {
// check if we have next. If we do, RETURN OURSELVES!
// if we don't even _have_ links, make one up
let next = "";
if (resp.headers.has("link")) {
const links = {
current: "",
next: "",
first: "",
last: "",
raw: [""]
};
const link = resp.headers.get("link");
if (link === null) {
throw new Error("Undefined link");
} else {
links.raw = link.split(",");
}
// We don't necessarily have everything...
for (let i = 0; i < links.raw.length; i++) {
// split and engage
const tmp = links.raw[i].split(";");
if (tmp[1].includes("current")) {
links.current = decodeURI(tmp[0].slice(1, -1));
} else if (tmp[1].includes("next")) {
links.next = decodeURI(tmp[0].slice(1, -1));
} else if (tmp[1].includes("first")) {
links.first = decodeURI(tmp[0].slice(1, -1));
} else if (tmp[1].includes("last")) {
links.last = decodeURI(tmp[0].slice(1, -1));
}
}
// each follows the same formula:
// 1. Split via the ";" - we only need the first part!
// 2. slice it to remove the opening and closing <>
// 3. Decode it!
if (links.current == links.last || links.next === "") {
// we are at the last page; finished!
next = "";
} else {
next = links.next;
}
}
// if we do NOT have next, just return resp?
if (next === "") {
return resp.json();
} else {
const pager = getPage(config, next)
.then(async pagerResponse => {
// concatenate with our own response!
const current = await resp.json();
// concat and return
return current.concat(pagerResponse);
});
return pager;
}
});
} | CS1371/canvas-quiz-parser | src/canvas/getStudents.ts | TypeScript |
FunctionDeclaration | /**
* getStudents will fetch all available students from the specified course.
* This also uses the Canvas API, but only expects the basic information to
* be given. Incidentally, this also returns a promise that resolves to the
* array of all canvas students.
* @param config The canvas configuration
* @returns A Promise that resolves to an array of Canvas Students. @see CanvasStudent for more information.
*/
export default async function getStudents(config: CanvasConfig): Promise<CanvasStudent[]> {
const studentApi = `https://${config.site}/api/v1/courses/${config.course}/users?enrollment_type[]=student&include[]=enrollment&per_page=100`;
return getPage(config, studentApi);
} | CS1371/canvas-quiz-parser | src/canvas/getStudents.ts | TypeScript |
ArrowFunction |
resp => {
// check if we have next. If we do, RETURN OURSELVES!
// if we don't even _have_ links, make one up
let next = "";
if (resp.headers.has("link")) {
const links = {
current: "",
next: "",
first: "",
last: "",
raw: [""]
};
const link = resp.headers.get("link");
if (link === null) {
throw new Error("Undefined link");
} else {
links.raw = link.split(",");
}
// We don't necessarily have everything...
for (let i = 0; i < links.raw.length; i++) {
// split and engage
const tmp = links.raw[i].split(";");
if (tmp[1].includes("current")) {
links.current = decodeURI(tmp[0].slice(1, -1));
} else if (tmp[1].includes("next")) {
links.next = decodeURI(tmp[0].slice(1, -1));
} else if (tmp[1].includes("first")) {
links.first = decodeURI(tmp[0].slice(1, -1));
} else if (tmp[1].includes("last")) {
links.last = decodeURI(tmp[0].slice(1, -1));
}
}
// each follows the same formula:
// 1. Split via the ";" - we only need the first part!
// 2. slice it to remove the opening and closing <>
// 3. Decode it!
if (links.current == links.last || links.next === "") {
// we are at the last page; finished!
next = "";
} else {
next = links.next;
}
}
// if we do NOT have next, just return resp?
if (next === "") {
return resp.json();
} else {
const pager = getPage(config, next)
.then(async pagerResponse => {
// concatenate with our own response!
const current = await resp.json();
// concat and return
return current.concat(pagerResponse);
});
return pager;
}
} | CS1371/canvas-quiz-parser | src/canvas/getStudents.ts | TypeScript |
ArrowFunction |
async pagerResponse => {
// concatenate with our own response!
const current = await resp.json();
// concat and return
return current.concat(pagerResponse);
} | CS1371/canvas-quiz-parser | src/canvas/getStudents.ts | TypeScript |
FunctionDeclaration | // reducers
function todosReducer(state: Todos, action: Action): Todos {
if (action.type === 'TODO_LOADED') {
return { selected: action.payload };
} else {
return state;
}
} | Domratchev/nx | packages/nx/spec/data-persistence.spec.ts | TypeScript |
FunctionDeclaration |
function userReducer(state: string, action: Action): string {
return 'bob';
} | Domratchev/nx | packages/nx/spec/data-persistence.spec.ts | TypeScript |
FunctionDeclaration |
function userReducer() {
return 'bob';
} | Domratchev/nx | packages/nx/spec/data-persistence.spec.ts | TypeScript |
ArrowFunction |
() => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [RootCmp, TodoComponent],
imports: [
StoreModule.forRoot({ todos: todosReducer, user: userReducer }),
StoreRouterConnectingModule,
RouterTestingModule.withRoutes([
{ path: 'todo/:id', component: TodoComponent }
]),
NxModule.forRoot()
]
});
});
describe('successful navigation', () => {
@Injectable()
class TodoEffects {
@Effect()
loadTodo = this.s.navigation(TodoComponent, {
run: (a, state) => {
return {
type: 'TODO_LOADED',
payload: { id: a.params['id'], user: state.user }
};
},
onError: () => null
});
constructor(private s: DataPersistence<TodosState>) {}
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [EffectsModule.forRoot([TodoEffects])]
});
});
it('should work', fakeAsync(() => {
const root = TestBed.createComponent(RootCmp);
const router: Router = TestBed.get(Router);
router.navigateByUrl('/todo/123');
tick(0);
root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).toContain('ID 123');
expect(root.elementRef.nativeElement.innerHTML).toContain('User bob');
}));
});
describe('`run` throwing an error', () => {
@Injectable()
class TodoEffects {
@Effect()
loadTodo = this.s.navigation(TodoComponent, {
run: (a, state) => {
if (a.params['id'] === '123') {
throw new Error('boom');
} else {
return {
type: 'TODO_LOADED',
payload: { id: a.params['id'], user: state.user }
};
}
},
onError: (a, e) => ({ type: 'ERROR', payload: { error: e } })
});
constructor(private s: DataPersistence<TodosState>) {}
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [EffectsModule.forRoot([TodoEffects])]
});
});
it('should work', fakeAsync(() => {
const root = TestBed.createComponent(RootCmp);
const router: Router = TestBed.get(Router);
let actions: any[] = [];
TestBed.get(Actions).subscribe((a: any) => actions.push(a));
router.navigateByUrl('/todo/123');
tick(0);
root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123');
expect(actions.map(a => a.type)).toContain('ERROR');
expect(
actions.find(a => a.type === 'ERROR').payload.error.message
).toEqual('boom');
// can recover after an error
router.navigateByUrl('/todo/456');
tick(0);
root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).toContain('ID 456');
}));
});
describe('`run` returning an error observable', () => {
@Injectable()
class TodoEffects {
@Effect()
loadTodo = this.s.navigation(TodoComponent, {
run: (a, state) => {
if (a.params['id'] === '123') {
return throwError('boom');
} else {
return {
type: 'TODO_LOADED',
payload: { id: a.params['id'], user: state.user }
};
}
},
onError: (a, e) => ({ type: 'ERROR', payload: { error: e } })
});
constructor(private s: DataPersistence<TodosState>) {}
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [EffectsModule.forRoot([TodoEffects])]
});
});
it('should work', fakeAsync(() => {
const root = TestBed.createComponent(RootCmp);
const router: Router = TestBed.get(Router);
let actions: any[] = [];
TestBed.get(Actions).subscribe((a: any) => actions.push(a));
router.navigateByUrl('/todo/123');
tick(0);
root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123');
expect(actions.map(a => a.type)).toContain('ERROR');
expect(actions.find(a => a.type === 'ERROR').payload.error).toEqual(
'boom'
);
router.navigateByUrl('/todo/456');
tick(0);
root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).toContain('ID 456');
}));
});
} | Domratchev/nx | packages/nx/spec/data-persistence.spec.ts | TypeScript |