type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
MethodDeclaration
|
/**
* Save the idp-url again
*/
saveOptions() {
if (this.form.valid) {
this.workspace.proxyConfiguration.proxyUrl = this.form.controls['proxyUrl'].value;
this.workspace.proxyConfiguration.proxyProtocol = this.form.controls['proxyProtocol'].value;
this.workspace.proxyConfiguration.proxyPort = this.form.controls['proxyPort'].value;
this.workspace.proxyConfiguration.username = this.form.controls['proxyUsername'].value;
this.workspace.proxyConfiguration.password = this.form.controls['proxyPassword'].value;
this.workspaceService.updateProxyConfiguration(this.workspace.proxyConfiguration);
this.workspace.defaultRegion = this.selectedRegion;
this.workspaceService.updateDefaultRegion(this.workspace.defaultRegion);
this.workspace.defaultLocation = this.selectedLocation;
this.workspaceService.updateDefaultLocation(this.workspace.defaultLocation);
// this.workspace.awsSsoConfiguration.browserOpening = this.selectedBrowserOpening;
// this.workspaceService.updateBrowserOpening(this.selectedBrowserOpening);
if (this.checkIfNeedDialogBox()) {
this.appService.confirmDialog('You\'ve set a proxy url: the app must be restarted to update the configuration.', (res) => {
if (res !== Constants.confirmClosed) {
this.loggingService.logger('User have set a proxy url: the app must be restarted to update the configuration.', LoggerLevel.info, this);
this.appService.restart();
}
});
} else {
this.loggingService.logger('Option saved.', LoggerLevel.info, this, JSON.stringify(this.form.getRawValue(), null, 3));
this.loggingService.toast('Option saved.', ToastLevel.info, 'Options');
this.router.navigate(['/sessions', 'session-selected']).then(_ => {});
}
}
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Check if we need a dialog box to request restarting the application
*/
checkIfNeedDialogBox() {
return this.form.controls['proxyUrl'].value !== undefined &&
this.form.controls['proxyUrl'].value !== null &&
(this.form.controls['proxyUrl'].dirty ||
this.form.controls['proxyProtocol'].dirty ||
this.form.controls['proxyPort'].dirty ||
this.form.controls['proxyUsername'].dirty ||
this.form.controls['proxyPassword'].dirty);
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Return to home screen
*/
goBack() {
this.router.navigate(['/', 'sessions', 'session-selected']).then(_ => {});
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
manageIdpUrl(id) {
const idpUrl = this.workspaceService.getIdpUrl(id);
if (this.form.get('idpUrl').value !== '') {
if (!idpUrl) {
this.workspaceService.addIdpUrl({ id: uuid.v4(), url: this.form.get('idpUrl').value });
} else {
this.workspaceService.updateIdpUrl(id, this.form.get('idpUrl').value);
}
}
this.editingIdpUrl = false;
this.idpUrlValue = undefined;
this.form.get('idpUrl').setValue('');
this.workspace = this.workspaceService.getWorkspace();
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
editIdpUrl(id) {
const idpUrl = this.workspace.idpUrls.filter(u => u.id === id)[0];
this.idpUrlValue = idpUrl;
this.form.get('idpUrl').setValue(idpUrl.url);
this.editingIdpUrl = true;
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
deleteIdpUrl(id) {
// Assumable sessions with this id
this.sessionService = this.sessionProviderService.getService(SessionType.awsIamRoleFederated);
let sessions = this.sessionService.list().filter(s => (s as AwsIamRoleFederatedSession).idpUrlId === id);
// Add iam Role Chained from iam role iam_federated_role
sessions.forEach(parent => {
const childs = this.sessionService.listIamRoleChained(parent);
sessions = sessions.concat(childs);
});
// Get only names for display
let sessionsNames = sessions.map(s => `<li><div class="removed-sessions"><b>${s.sessionName}</b> - <small>${(s as AwsIamRoleFederatedSession).roleArn.split('/')[1]}</small></div></li>`);
if (sessionsNames.length === 0) {
sessionsNames = ['<li><b>no sessions</b></li>'];
}
// Ask for deletion
this.appService.confirmDialog(`Deleting this Idp url will also remove these sessions: <br><ul>${sessionsNames.join('')}</ul>Do you want to proceed?`, (res) => {
if (res !== Constants.confirmClosed) {
this.loggingService.logger(`Removing idp url with id: ${id}`, LoggerLevel.info, this);
this.workspaceService.removeIdpUrl(id);
sessions.forEach(session => {
this.sessionService.delete(session.sessionId);
});
this.workspace = this.workspaceService.getWorkspace();
}
});
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
async manageAwsProfile(id: string | number) {
const profileIndex = this.workspaceService.getWorkspace().profiles.findIndex(p => p.id === id.toString());
if (this.form.get('awsProfile').value !== '') {
if (profileIndex === -1) {
this.workspaceService.addProfile({ id: uuid.v4(), name: this.form.get('awsProfile').value });
} else {
this.workspaceService.updateProfile(id.toString(), this.form.get('awsProfile').value);
for(let i = 0; i < this.workspaceService.sessions.length; i++) {
const sess = this.workspaceService.sessions[i];
this.sessionService = this.sessionProviderService.getService(sess.type);
if( (sess as any).profileId === id.toString()) {
if ((sess as any).status === SessionStatus.active) {
await this.sessionService.stop(sess.sessionId);
await this.sessionService.start(sess.sessionId);
}
}
}
}
}
this.editingAwsProfile = false;
this.awsProfileValue = undefined;
this.form.get('awsProfile').setValue('');
this.workspace = this.workspaceService.getWorkspace();
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
editAwsProfile(id: string) {
const profile = this.workspace.profiles.filter(u => u.id === id)[0];
this.awsProfileValue = profile;
this.form.get('awsProfile').setValue(profile.name);
this.editingAwsProfile = true;
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
MethodDeclaration
|
deleteAwsProfile(id: string) {
// With profile
const sessions = this.awsSessionService.list().filter(sess => (sess as any).profileId === id);
// Get only names for display
let sessionsNames = sessions.map(s => `<li><div class="removed-sessions"><b>${s.sessionName}</b> - <small>${(s as AwsIamRoleFederatedSession).roleArn ? (s as AwsIamRoleFederatedSession).roleArn.split('/')[1] : ''}</small></div></li>`);
if (sessionsNames.length === 0) {
sessionsNames = ['<li><b>no sessions</b></li>'];
}
// Ask for deletion
this.appService.confirmDialog(`Deleting this profile will set default to these sessions: <br><ul>${sessionsNames.join('')}</ul>Do you want to proceed?`, async (res) => {
if (res !== Constants.confirmClosed) {
this.loggingService.logger(`Reverting to default profile with id: ${id}`, LoggerLevel.info, this);
this.workspaceService.removeProfile(id);
// Reverting all sessions to default profile
for(let i = 0; i < sessions.length; i++) {
const sess = sessions[i];
this.sessionService = this.sessionProviderService.getService(sess.type);
let wasActive = false;
if ((sess as any).status === SessionStatus.active) {
wasActive = true;
await this.sessionService.stop(sess.sessionId);
}
(sess as any).profileId = this.workspaceService.getDefaultProfileId();
this.sessionService.update(sess.sessionId, sess);
if(wasActive) {
this.sessionService.start(sess.sessionId);
}
}
this.workspace = this.workspaceService.getWorkspace();
}
});
}
|
dnsmichi/leapp
|
src/app/components/shared/profile-page/profile-page.component.ts
|
TypeScript
|
FunctionDeclaration
|
export function validate(params: AddTokenParams, balances: Balances): ErrorState {
const { address } = params
if (!address) {
return invalidInput('address', 'Token address is required')
}
if (!isValidAddress(address)) {
logger.error(`Invalid token address: ${address}`)
return invalidInput('address', 'Invalid token address')
}
if (hasToken(balances, address)) {
logger.error(`Token already exists in wallet: ${address}`)
return invalidInput('address', 'Token already exists')
}
return { isValid: true }
}
|
Chimoney/celo-web-wallet
|
src/features/wallet/balances/addToken.ts
|
TypeScript
|
FunctionDeclaration
|
function* addToken(params: AddTokenParams) {
const balances = yield* select((state: RootState) => state.wallet.balances)
validateOrThrow(() => validate(params, balances), 'Invalid Token')
const newToken = yield* call(getTokenInfo, params.address)
yield* put(addTokenAction(newToken))
yield* put(fetchBalancesActions.trigger())
}
|
Chimoney/celo-web-wallet
|
src/features/wallet/balances/addToken.ts
|
TypeScript
|
FunctionDeclaration
|
export function* addTokensById(ids: Set<string>) {
for (const id of ids) {
try {
const knownToken = findTokenById(id)
if (!knownToken) continue
const newToken = yield* call(getTokenInfo, knownToken.address, knownToken)
yield* put(addTokenAction(newToken))
} catch (error) {
logger.error(`Failed to add token ${id}`, error)
}
}
}
|
Chimoney/celo-web-wallet
|
src/features/wallet/balances/addToken.ts
|
TypeScript
|
FunctionDeclaration
|
async function getTokenInfo(tokenAddress: string, knownToken?: Token): Promise<Token> {
knownToken = knownToken || findTokenByAddress(tokenAddress)
const contract = getTokenContract(tokenAddress)
// Note this assumes the existence of decimals, symbols, and name methods,
// which are technically optional. May revisit later
const symbolP: Promise<string> = contract.symbol()
const nameP: Promise<string> = contract.name()
const decimalsP: Promise<BigNumberish> = contract.decimals()
const [symbol, name, decimalsBN] = await Promise.all([symbolP, nameP, decimalsP])
const decimals = BigNumber.from(decimalsBN).toNumber()
if (!symbol || typeof symbol !== 'string') throw new Error('Invalid token symbol')
if (!name || typeof name !== 'string') throw new Error('Invalid token name')
if (decimals !== CELO.decimals) throw new Error('Invalid token decimals') // TODO only 18 is supported atm
return {
id: symbol,
symbol: symbol.substring(0, 8),
name,
color: knownToken?.color || Color.accentBlue,
minValue: CELO.minValue,
displayDecimals: CELO.displayDecimals,
address: normalizeAddress(tokenAddress),
decimals,
chainId: config.chainId,
}
}
|
Chimoney/celo-web-wallet
|
src/features/wallet/balances/addToken.ts
|
TypeScript
|
ArrowFunction
|
(state: RootState) => state.wallet.balances
|
Chimoney/celo-web-wallet
|
src/features/wallet/balances/addToken.ts
|
TypeScript
|
ArrowFunction
|
() => validate(params, balances)
|
Chimoney/celo-web-wallet
|
src/features/wallet/balances/addToken.ts
|
TypeScript
|
ArrowFunction
|
(event) => this.onOkButtonClicked(event)
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
ArrowFunction
|
(event) => this.onCancelButtonClicked(event)
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
ArrowFunction
|
element => {
element.disabled = block;
}
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
ArrowFunction
|
(user) => {
//console.log(user.username + " :: " + user.computerName + " :: " + user.threadId + " :: " + user.server + " :: " + this.message);
this.server.sendUserMessage(
user.username,
user.computerName,
user.threadId,
user.server,
this.message,
user.environment);
progressbar.progress += step;
}
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
ClassDeclaration
|
@customElement('monitor-send-message-dialog')
export class MonitorSendMessageDialog extends MonitorDialog {
get message(): string {
let message = this.renderRoot.querySelector<MonitorTextInput>('#message').value;
return message;
}
@property({ type: String, reflect: true, attribute: true })
get progress(): ProgressOption {
return super.progress;
}
set progress(value: ProgressOption) {
super.progress = value;
}
server: TdsMonitorServer;
users: Array<MonitorUser>;
constructor(server: TdsMonitorServer, users: Array<MonitorUser>) {
super({
escClose: true,
buttons: [
{
text: i18n.localize("SEND", "Send"),
click: (event) => this.onOkButtonClicked(event)
},
{
text: i18n.cancel(),
click: (event) => this.onCancelButtonClicked(event)
}
]
});
this.title = i18n.localize("SEND_MESSAGE", "Send Message");
this.progress = 'hidden';
this.server = server;
this.users = users;
}
get body() {
return html`
<monitor-text-input id="message" tabindex="1" type="textarea"></monitor-text-input>
`;
}
static get styles(): CSSResult {
return style;
}
blockControls(block: boolean) {
this.renderRoot.querySelectorAll<MonitorTextInput>('monitor-text-input')
.forEach((element => {
element.disabled = block;
}));
this.renderRoot.querySelectorAll<MonitorButton>('monitor-button')
.forEach((element => {
element.disabled = block;
}));
}
onOkButtonClicked(event: Event) {
this.blockControls(true);
this.progress = 'visible';
//Validar inputs aqui
if (this.message.length == 0) {
// alert ou outro modal com o erro ???
return;
}
let progressbar = this.renderRoot.querySelector('monitor-linear-progress'),
step = 1 / this.users.length;
progressbar.indeterminate = false;
progressbar.progress = 0;
this.users.forEach((user) => {
//console.log(user.username + " :: " + user.computerName + " :: " + user.threadId + " :: " + user.server + " :: " + this.message);
this.server.sendUserMessage(
user.username,
user.computerName,
user.threadId,
user.server,
this.message,
user.environment);
progressbar.progress += step;
})
this.blockControls(false);
this.progress = 'hidden';
this.close();
}
onCancelButtonClicked(event: Event) {
this.cancel();
}
}
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
MethodDeclaration
|
blockControls(block: boolean) {
this.renderRoot.querySelectorAll<MonitorTextInput>('monitor-text-input')
.forEach((element => {
element.disabled = block;
}));
this.renderRoot.querySelectorAll<MonitorButton>('monitor-button')
.forEach((element => {
element.disabled = block;
}));
}
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
MethodDeclaration
|
onOkButtonClicked(event: Event) {
this.blockControls(true);
this.progress = 'visible';
//Validar inputs aqui
if (this.message.length == 0) {
// alert ou outro modal com o erro ???
return;
}
let progressbar = this.renderRoot.querySelector('monitor-linear-progress'),
step = 1 / this.users.length;
progressbar.indeterminate = false;
progressbar.progress = 0;
this.users.forEach((user) => {
//console.log(user.username + " :: " + user.computerName + " :: " + user.threadId + " :: " + user.server + " :: " + this.message);
this.server.sendUserMessage(
user.username,
user.computerName,
user.threadId,
user.server,
this.message,
user.environment);
progressbar.progress += step;
})
this.blockControls(false);
this.progress = 'hidden';
this.close();
}
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
MethodDeclaration
|
onCancelButtonClicked(event: Event) {
this.cancel();
}
|
totvs/tds-monitor-frontend
|
src/main/ts/monitor-send-message-dialog.ts
|
TypeScript
|
FunctionDeclaration
|
export function sendTelegramMessage(link: Link, store: Store) {
if (telegram.accessToken && telegram.chatId) {
logger.debug('↗ sending telegram message');
(async () => {
const message = Print.productInStock(link);
const results = [];
for (const chatId of telegram.chatId) {
try {
results.push(
client.sendMessage(
chatId,
`${Print.inStock(link, store)}\n${message}`
)
);
logger.info('✔ telegram message sent');
} catch (error: unknown) {
logger.error("✖ couldn't send telegram message", error);
}
}
await Promise.all(results);
})();
}
}
|
sehuang/streetmerchant
|
src/notification/telegram.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const message = Print.productInStock(link);
const results = [];
for (const chatId of telegram.chatId) {
try {
results.push(
client.sendMessage(
chatId,
`${Print.inStock(link, store)}\n${message}`
)
);
logger.info('✔ telegram message sent');
} catch (error: unknown) {
logger.error("✖ couldn't send telegram message", error);
}
}
await Promise.all(results);
}
|
sehuang/streetmerchant
|
src/notification/telegram.ts
|
TypeScript
|
ArrowFunction
|
({ num }: { num: number }) => {
const n = num % colors.length
const color = colors[n]
return (
<svg viewBox="0 0 24 24" fill={color}>
<path d="M21.5 24h-19c-1.379 0-2.5-1.122-2.5-2.5v-19c0-1.379 1.122-2.5 2.5-2.5h19c1.379 0 2.5 1.122 2.5 2.5v19c0 1.379-1.122 2.5-2.5 2.5zm-19-23c-.827 0-1.5.673-1.5 1.5v19c0 .827.673 1.5 1.5 1.5h19c.827 0 1.5-.673 1.5-1.5v-19c0-.827-.673-1.5-1.5-1.5h-19zM15.598 12.385zM19.438 15.417l-.002-.005v-.001c-.875-2.226-2.484-3.054-3.445-3.549l-.273-.143c.029-.497-.025-1.034-.167-1.599l-.128.032.123-.044c-.765-2.152-1.757-2.585-2.632-2.967l-.006-.003-.535-2.121c.357-.065.628-.375.628-.752.001-.423-.342-.765-.765-.765s-.766.342-.766.765c0 .358.248.657.581.74l-.825 1.654-.014-.003-.024-.003c-1.053-.033-1.842.369-2.5.947-.633-.322-1.515-.729-2.158-1.814.107-.12.174-.276.174-.45 0-.375-.303-.678-.678-.678s-.678.303-.678.678.303.678.678.678l.221-.04c.416.597 1.09 1.181 1.347 2.828l-.072.091.104.081-.112-.067c-1.157 1.914-.793 4.248.207 5.37-.998 2.546-1.035 4.681-.097 5.868l.002.002.003.003c.119.162.313.233.524.233.189 0 .39-.057.559-.154.312-.179.441-.459.326-.713l-.12.054.119-.056c-.581-1.243-.474-2.713.314-4.37.4.131.778.208 1.145.234l.139.73c.264 1.418.514 2.757 1.297 4.006.132.264.453.387.777.387.122 0 .245-.018.357-.051.385-.116.591-.399.537-.738l-.129.021.125-.042c-.204-.606-.431-1.146-.649-1.67-.373-.894-.725-1.742-.891-2.737.407-.042.797-.129 1.161-.261.825.692 1.661 1.492 2.743 3.406h.001c.072.14.224.215.41.215.105 0 .222-.024.339-.073.365-.155.652-.531.477-1.006v-.001c-.432-1.849-1.426-2.778-2.428-3.547.162-.175.311-.366.442-.576.75.399 1.878 1.005 3.127 2.766l.047.067.011-.008c.151.156.317.24.48.24.096 0 .191-.027.279-.084.306-.194.439-.662.29-1.005zm-8.878-2.493c-.947 0-1.713-.767-1.713-1.713s.767-1.713 1.713-1.713c.947 0 1.713.767 1.713 1.713s-.767 1.713-1.713 1.713zm6.587 4.648l-.084.021v-.001l.084-.02zm-2.007-5.312zm.022 1.006zM11.225 11.604c0 .385-.312.697-.697.697s-.697-.312-.697-.697c0-.385.312-.697.697-.697s.697.312.697.697z" />
</svg>
|
Tarik02/habra
|
src/components/svg/UserPlaceholder.tsx
|
TypeScript
|
ArrowFunction
|
(): Struct<string, null> => {
return define<string>('email', (value) => isEmail(value));
}
|
MunifTanjim/toolbox
|
apps/backend/src/libs/validator/index.ts
|
TypeScript
|
ArrowFunction
|
(value) => isEmail(value)
|
MunifTanjim/toolbox
|
apps/backend/src/libs/validator/index.ts
|
TypeScript
|
ArrowFunction
|
(): Struct<string, null> => {
return size(string(), 27);
}
|
MunifTanjim/toolbox
|
apps/backend/src/libs/validator/index.ts
|
TypeScript
|
ArrowFunction
|
result => result.insertedId
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
ClassDeclaration
|
@Entity({ name: 'user' })
export class UserEntity extends MongoEntity<User> implements User {
@Column()
_id!: ObjectId;
@Column({ index: true, unique: true })
id!: number;
@Column({ index: true, unique: true })
idstr!: string;
@Column()
class!: number;
@Column()
screen_name!: string;
@Column()
name!: string;
@Column()
province!: string;
@Column()
city!: string;
@Column()
location!: string;
@Column()
description!: string;
@Column()
url!: string;
@Column()
profile_image_url!: string;
@Column()
cover_image_phone!: string;
@Column()
profile_url!: string;
@Column()
domain!: string;
@Column()
weihao!: string;
@Column()
gender!: string;
@Column()
followers_count!: number;
@Column()
friends_count!: number;
@Column()
pagefriends_count!: number;
@Column()
statuses_count!: number;
@Column()
video_status_count!: number;
@Column()
video_play_count!: number;
@Column()
favourites_count!: number;
@Column()
created_at!: string;
@Column()
following!: boolean;
@Column()
allow_all_act_msg!: boolean;
@Column()
geo_enabled!: boolean;
@Column()
verified!: boolean;
@Column()
verified_type!: number;
@Column()
remark!: string;
@Column()
email!: string;
@Column()
insecurity!: Insecurity;
@Column()
ptype!: number;
@Column()
allow_all_comment!: boolean;
@Column()
avatar_large!: string;
@Column()
avatar_hd!: string;
@Column()
verified_reason!: string;
@Column()
verified_trade!: string;
@Column()
verified_reason_url!: string;
@Column()
verified_source!: string;
@Column()
verified_source_url!: string;
@Column()
follow_me!: boolean;
@Column()
like!: boolean;
@Column()
like_me!: boolean;
@Column()
online_status!: number;
@Column()
bi_followers_count!: number;
@Column()
lang!: string;
@Column()
star!: number;
@Column()
mbtype!: number;
@Column()
mbrank!: number;
@Column()
block_word!: number;
@Column()
block_app!: number;
@Column()
credit_score!: number;
@Column()
user_ability!: number;
@Column()
urank!: number;
@Column()
story_read_state!: number;
@Column()
vclub_member!: number;
@Column()
is_teenager!: number;
@Column()
is_guardian!: number;
@Column()
is_teenager_list!: number;
@Column()
pc_new!: number;
@Column()
special_follow!: boolean;
@Column()
planet_video!: number;
@Column()
video_mark!: number;
@Column()
live_status!: number;
@Column()
tab_manage!: string;
@Column()
cardid!: string;
@Column()
avatargj_id!: string;
@Column()
verified_state?: number | undefined;
@Column()
verified_level?: number | undefined;
@Column()
verified_type_ext?: number | undefined;
@Column()
has_service_tel?: boolean | undefined;
@Column()
verified_reason_modified!: string;
@Column()
verified_contact_name!: string;
@Column()
verified_contact_email!: string;
@Column()
verified_contact_mobile!: string;
@Column()
cover_image!: string;
@Column()
unicom_free_pc!: string;
async getRandomList({ take }: Pick<PaginationParam, 'take'>) {
return { list: await this.collection.aggregate([{ $sample: { size: take } }]).toArray() };
}
async insertOne(user: User) {
const id = await this.collection
.insertOne(user)
.then(result => result.insertedId);
return this.collection.findOne({ _id: new ObjectId(id) });
}
async deleteOne(id: UserID) {
await this.collection.deleteOne({ _id: new ObjectId(id) });
return [id];
}
async updateOne(id: UserID, user: Partial<User>) {
await this.collection.updateOne(
{ _id: new ObjectId(id) },
{ $set: user },
);
return this.collection.findOne({ _id: new ObjectId(id) });
}
async findOne(id: UserID) {
return this.collection.findOne({ id });
}
}
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
TypeAliasDeclaration
|
export type UserCollection = UserEntity['collection'];
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
MethodDeclaration
|
async getRandomList({ take }: Pick<PaginationParam, 'take'>) {
return { list: await this.collection.aggregate([{ $sample: { size: take } }]).toArray() };
}
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
MethodDeclaration
|
async insertOne(user: User) {
const id = await this.collection
.insertOne(user)
.then(result => result.insertedId);
return this.collection.findOne({ _id: new ObjectId(id) });
}
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
MethodDeclaration
|
async deleteOne(id: UserID) {
await this.collection.deleteOne({ _id: new ObjectId(id) });
return [id];
}
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
MethodDeclaration
|
async updateOne(id: UserID, user: Partial<User>) {
await this.collection.updateOne(
{ _id: new ObjectId(id) },
{ $set: user },
);
return this.collection.findOne({ _id: new ObjectId(id) });
}
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
MethodDeclaration
|
async findOne(id: UserID) {
return this.collection.findOne({ id });
}
|
DevinDon/demo
|
apps/weibo-api/src/app/user/user.entity.ts
|
TypeScript
|
FunctionDeclaration
|
// import loadable from "@loadable/component"
// const Home = loadable(() => import("../Home"))
// const Login = loadable(() => import("../Login"))
export default function App() {
return (
<BrowserRouter>
<Suspense fallback={<Loading text="loading contents..." />}
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"terrace"*/"../Terrace")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"carrier"*/"../Carrier")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"home"*/"../Home")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"school" */"../School")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"cinema" */"../Cinema")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"court" */"../Court")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"transportation" */"../Transportation")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"cosmodrome" */"../Cosmodrome")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"dam" */"../Dam")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"gymnasium" */"../Gymnasium")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"hospital" */"../Hospital")
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
() => import(/*webpackChunkName:"bank" */'../Bank')
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
ArrowFunction
|
()=>import(/*webpackChunkName:"government" */'../Government')
|
WenJiang99/new-media-re
|
src/screens/App/index.tsx
|
TypeScript
|
FunctionDeclaration
|
export function validateXsd(): ThunkAction<Promise<void>, State, void, Action> {
return async (dispatch, getState) => {
dispatch({ type: Types.LoadValidation_Start } as LoadValidationStartAction);
const state = getState();
const projectRevision = currentProjectRevisionSelector(state);
if (!projectRevision) {
throw new Error("Missing project!");
}
const { projectData } = state;
const xsd = xsdToString(
projectData.xsd,
projectData.xsdAnalysis ? projectData.xsdAnalysis.determineXsdPrefixIncludingColon() : '',
projectRevision.baseUri,
);
const baseURI = projectRevision.baseUri || undefined;
let errors: ValidationError[];
try {
errors = await doValidation(xsd, baseURI);
} catch (err) {
dispatch({
type: Types.LoadValidation_Fail,
error: true,
payload: err,
} as LoadValidationFailAction);
return;
}
if (!errors.length) {
dispatch({
type: Types.LoadValidation_Finish,
payload: {},
} as LoadValidationFinishAction);
}
const result: Dictionary<ValidationError[]> = validateDuplicateAttributes(projectData.xsd);
function pushError(id: string, err: ValidationError) {
if (!result[id]) {
result[id] = [] as ValidationError[];
}
result[id].push(err);
}
const li = calculateLineInformation(projectData.xsd);
const startElementLines = li.elements.map(([line]) => line);
for (const err of errors) {
const idx = le(startElementLines, err.line);
if (idx === -1) {
continue;
}
const [_start, _end, id] = li.elements[idx];
const attrs = li.attributes.get(id);
if (attrs) {
const attrStartColumns = attrs.map(([start]) => start);
const attrIdx = le(attrStartColumns, err.column);
if (attrIdx !== -1) {
const [start, len, id] = attrs[attrIdx];
if (start + len >= err.column) {
pushError(id, err);
continue;
}
}
}
pushError(id, err);
}
dispatch({
type: Types.LoadValidation_Finish,
payload: result,
} as LoadValidationFinishAction);
};
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
FunctionDeclaration
|
function pushError(id: string, err: ValidationError) {
if (!result[id]) {
result[id] = [] as ValidationError[];
}
result[id].push(err);
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
FunctionDeclaration
|
function calculateLineInformation(tree: Dictionary<XsdElement>): RowColumnResult {
const root = xsdRootElementSelector(tree);
if (!root) {
throw new Error("Missing root element.");
}
// First line is always <?xml> header
const [res] = calculateElementPositions(tree, root, 2, 1, 2);
return res;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
FunctionDeclaration
|
function calculateElementPositions(
tree: Dictionary<XsdElement>,
el: XsdElement,
baseRow: number,
baseColumn: number,
indent: number,
): [RowColumnResult, number] {
const result: RowColumnResult = {
attributes: new Map(),
elements: [],
};
const attributes = values(el.attributes)
.sort((a, b) => a.position - b.position);
let curAttrPos = baseColumn + el.name.length + 1; // Element Name + <
// Get the map for the corresponding element
let attrMap = result.attributes.get(el.id);
if (!attrMap) {
attrMap = [];
result.attributes.set(el.id, attrMap);
}
for (const attr of attributes) {
// Attribute name + value + ="" + leading spacing
const length = attr.name.length + stringifier.attEscape(attr.value).length + 4;
attrMap.push([curAttrPos, length, attr.id]);
curAttrPos += length;
}
if (!el.content) {
result.elements.push([baseRow, 1, el.id]);
return [result, 1];
} else if (typeof el.content === 'string') {
const newlineCount = countNewlines(el.content);
result.elements.push([baseRow, newlineCount + 1, el.id]);
return [result, newlineCount + 1];
} else {
let childLength = 0;
const childEls: [number, number, string][] = [];
// Recurse through all children
for (const child of el.content.map(id => tree[id]).filter(el => el)) {
const [res, length] = calculateElementPositions(
tree,
child,
baseRow + childLength + 1,
baseColumn + indent,
indent,
);
childLength += length;
for (const [k, v] of res.attributes.entries()) {
result.attributes.set(k, v);
}
// Push into a temporary array first to preserve order
childEls.push(...res.elements);
}
// Insert current element first to preserve order, then insert child elements
result.elements.push([baseRow, childLength + 2, el.id]);
result.elements.push(...childEls);
return [result, childLength + 2]; // Start and end nodes
}
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
FunctionDeclaration
|
function countNewlines(str: string): number {
return [...str].filter(ch => ch === '\n').length;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
FunctionDeclaration
|
async function doValidation(xsd: string, baseURI: string | undefined): Promise<ValidationError[]> {
const resp = await fetch(`${API_BACKEND_URL}/validate`, {
body: JSON.stringify({ xsd, baseURI }),
method: 'post',
headers: {
'Accept': JSON_MIME,
'Content-Type': JSON_MIME,
},
});
const body = await resp.json();
return body.success || !body.errors ? [] : body.errors;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
FunctionDeclaration
|
function validateDuplicateAttributes(xsd: Dictionary<XsdElement>): Dictionary<ValidationError[]> {
const result = {};
values(xsd).forEach(element => {
const attributes = values(element.attributes);
const counted = attributes.reduce(
(store, attr) => Object.assign(store, { [attr.name]: (store[attr.name] || 0) + 1 }),
{},
);
Object.keys(counted)
.filter(name => counted[name] > 1)
.forEach(name => {
attributes.filter(attr => attr.name === name)
.forEach(attr => result[attr.id] = [{
column: 0,
line: 0,
// tslint:disable-next-line:max-line-length
message: `Duplicate attribute '${name}'. This will lead to unexpected results in the final XSD.`,
}]);
});
});
return result;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
async (dispatch, getState) => {
dispatch({ type: Types.LoadValidation_Start } as LoadValidationStartAction);
const state = getState();
const projectRevision = currentProjectRevisionSelector(state);
if (!projectRevision) {
throw new Error("Missing project!");
}
const { projectData } = state;
const xsd = xsdToString(
projectData.xsd,
projectData.xsdAnalysis ? projectData.xsdAnalysis.determineXsdPrefixIncludingColon() : '',
projectRevision.baseUri,
);
const baseURI = projectRevision.baseUri || undefined;
let errors: ValidationError[];
try {
errors = await doValidation(xsd, baseURI);
} catch (err) {
dispatch({
type: Types.LoadValidation_Fail,
error: true,
payload: err,
} as LoadValidationFailAction);
return;
}
if (!errors.length) {
dispatch({
type: Types.LoadValidation_Finish,
payload: {},
} as LoadValidationFinishAction);
}
const result: Dictionary<ValidationError[]> = validateDuplicateAttributes(projectData.xsd);
function pushError(id: string, err: ValidationError) {
if (!result[id]) {
result[id] = [] as ValidationError[];
}
result[id].push(err);
}
const li = calculateLineInformation(projectData.xsd);
const startElementLines = li.elements.map(([line]) => line);
for (const err of errors) {
const idx = le(startElementLines, err.line);
if (idx === -1) {
continue;
}
const [_start, _end, id] = li.elements[idx];
const attrs = li.attributes.get(id);
if (attrs) {
const attrStartColumns = attrs.map(([start]) => start);
const attrIdx = le(attrStartColumns, err.column);
if (attrIdx !== -1) {
const [start, len, id] = attrs[attrIdx];
if (start + len >= err.column) {
pushError(id, err);
continue;
}
}
}
pushError(id, err);
}
dispatch({
type: Types.LoadValidation_Finish,
payload: result,
} as LoadValidationFinishAction);
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
([line]) => line
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
([start]) => start
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
(a, b) => a.position - b.position
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
id => tree[id]
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
el => el
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
ch => ch === '\n'
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
element => {
const attributes = values(element.attributes);
const counted = attributes.reduce(
(store, attr) => Object.assign(store, { [attr.name]: (store[attr.name] || 0) + 1 }),
{},
);
Object.keys(counted)
.filter(name => counted[name] > 1)
.forEach(name => {
attributes.filter(attr => attr.name === name)
.forEach(attr => result[attr.id] = [{
column: 0,
line: 0,
// tslint:disable-next-line:max-line-length
message: `Duplicate attribute '${name}'. This will lead to unexpected results in the final XSD.`,
}]);
});
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
(store, attr) => Object.assign(store, { [attr.name]: (store[attr.name] || 0) + 1 })
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
name => counted[name] > 1
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
name => {
attributes.filter(attr => attr.name === name)
.forEach(attr => result[attr.id] = [{
column: 0,
line: 0,
// tslint:disable-next-line:max-line-length
message: `Duplicate attribute '${name}'. This will lead to unexpected results in the final XSD.`,
}]);
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
attr => attr.name === name
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
attr => result[attr.id] = [{
column: 0,
line: 0,
// tslint:disable-next-line:max-line-length
message: `Duplicate attribute '${name}'. This will lead to unexpected results in the final XSD.`,
}]
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface LoadValidationFailAction extends PayloadAction<Error> {
type: Types.LoadValidation_Fail;
error: true;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface LoadValidationFinishAction extends PayloadAction<Dictionary<ValidationError[]>> {
type: Types.LoadValidation_Finish;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface LoadValidationStartAction {
type: Types.LoadValidation_Start;
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
InterfaceDeclaration
|
interface RowColumnResult {
/**
* The starting and ending positions of attributes by corresponding element
* and attribute ID.
*/
attributes: Map<string, [number, number, string][]>;
/**
* The starting line and outer length of all elements.
*/
elements: [number, number, string][];
}
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
TypeAliasDeclaration
|
export type ValidationActions =
| LoadValidationFailAction
| LoadValidationFinishAction
| LoadValidationStartAction;
|
FIT-Mobility/dimo-tool-suite
|
frontend/src/actions/components/editor/validation.ts
|
TypeScript
|
ArrowFunction
|
() => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent]
}).compileComponents();
}));
it("should create the app", () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'crypto.com-chain-wallet'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual("crypto.com-chain-wallet");
});
}
|
calvinlauco/sample-chain-wallet
|
src/app/app.component.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent]
}).compileComponents();
}
|
calvinlauco/sample-chain-wallet
|
src/app/app.component.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual("crypto.com-chain-wallet");
}
|
calvinlauco/sample-chain-wallet
|
src/app/app.component.spec.ts
|
TypeScript
|
ArrowFunction
|
async (
client: AxiosHttpClient,
payload: {}
): Promise<AxiosResponse> => {
return client.request({
url: '',
method: 'post',
data: payload,
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
return [
{
jsonrpc: '2.0',
method: defaultSupportedMethods[0],
},
{
id: '1',
jsonrpc: '2.0',
method: defaultSupportedMethods[0],
},
{
id: 1,
method: defaultSupportedMethods[0],
},
{
id: 1,
jsonrpc: 2.0,
method: defaultSupportedMethods[0],
},
{ id: 1, jsonrpc: '2.0' },
{ id: 1, jsonrpc: '2.0', method: unsupportedMethod },
]
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
const fullnodeHandler: FullnodeHandler = new DummyFullnodeHandler()
let fullnodeRpcServer: FullnodeRpcServer
let baseUrl: string
let client: AxiosHttpClient
beforeEach(() => {
fullnodeRpcServer = new FullnodeRpcServer(fullnodeHandler, host, port)
fullnodeRpcServer.listen()
baseUrl = `http://${host}:${port}`
client = new AxiosHttpClient(baseUrl)
})
afterEach(() => {
if (!!fullnodeRpcServer) {
fullnodeRpcServer.close()
}
})
describe('single requests', () => {
it('should work for valid requests & methods', async () => {
const results: AxiosResponse[] = await Promise.all(
Array.from(defaultSupportedMethods).map((x) =>
request(client, { id: 1, jsonrpc: '2.0', method: x })
)
)
results.forEach((r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data['id'].should.equal(1)
r.data.should.haveOwnProperty('jsonrpc')
r.data['jsonrpc'].should.equal('2.0')
r.data.should.haveOwnProperty('result')
r.data['result'].should.equal(dummyResponse)
})
})
it('fails on bad format or method', async () => {
const results: AxiosResponse[] = await Promise.all(
getBadPayloads().map((x) => request(client, x))
)
results.forEach((r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data.should.haveOwnProperty('jsonrpc')
r.data.should.haveOwnProperty('error')
r.data['jsonrpc'].should.equal('2.0')
})
})
it('reverts properly', async () => {
const result: AxiosResponse = await request(client, {
id: 1,
jsonrpc: '2.0',
method: revertMethod,
})
result.status.should.equal(200)
result.data.should.haveOwnProperty('id')
result.data.should.haveOwnProperty('jsonrpc')
result.data.should.haveOwnProperty('error')
result.data['error'].should.haveOwnProperty('message')
result.data['error'].should.haveOwnProperty('code')
result.data['error']['message'].should.equal(
JSONRPC_ERRORS.REVERT_ERROR.message
)
result.data['error']['code'].should.equal(
JSONRPC_ERRORS.REVERT_ERROR.code
)
result.data['jsonrpc'].should.equal('2.0')
})
})
describe('batch requests', () => {
it('should work for valid requests & methods', async () => {
const batchRequest = Array.from(
defaultSupportedMethods
).map((method, id) => ({ jsonrpc: '2.0', id, method }))
const result: AxiosResponse = await request(client, batchRequest)
result.status.should.equal(200)
const results = result.data
results.forEach((r, id) => {
r.should.haveOwnProperty('id')
r['id'].should.equal(id)
r.should.haveOwnProperty('jsonrpc')
r['jsonrpc'].should.equal('2.0')
r.should.haveOwnProperty('result')
r['result'].should.equal(dummyResponse)
})
})
it('should fail on bad format or for valid requests & methods', async () => {
const result: AxiosResponse = await request(client, getBadPayloads())
result.status.should.equal(200)
const results = result.data
results.forEach((r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['jsonrpc'].should.equal('2.0')
})
})
it('should not allow batches of batches', async () => {
const batchOfBatches = Array.from(
defaultSupportedMethods
).map((method, id) => [{ jsonrpc: '2.0', id, method }])
const result: AxiosResponse = await request(client, batchOfBatches)
result.status.should.equal(200)
const results = result.data
results.forEach((r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['error'].should.haveOwnProperty('message')
r['error'].should.haveOwnProperty('code')
r['error']['message'].should.equal(
JSONRPC_ERRORS.INVALID_REQUEST.message
)
r['error']['code'].should.equal(JSONRPC_ERRORS.INVALID_REQUEST.code)
r['jsonrpc'].should.equal('2.0')
})
})
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
fullnodeRpcServer = new FullnodeRpcServer(fullnodeHandler, host, port)
fullnodeRpcServer.listen()
baseUrl = `http://${host}:${port}`
client = new AxiosHttpClient(baseUrl)
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
if (!!fullnodeRpcServer) {
fullnodeRpcServer.close()
}
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
it('should work for valid requests & methods', async () => {
const results: AxiosResponse[] = await Promise.all(
Array.from(defaultSupportedMethods).map((x) =>
request(client, { id: 1, jsonrpc: '2.0', method: x })
)
)
results.forEach((r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data['id'].should.equal(1)
r.data.should.haveOwnProperty('jsonrpc')
r.data['jsonrpc'].should.equal('2.0')
r.data.should.haveOwnProperty('result')
r.data['result'].should.equal(dummyResponse)
})
})
it('fails on bad format or method', async () => {
const results: AxiosResponse[] = await Promise.all(
getBadPayloads().map((x) => request(client, x))
)
results.forEach((r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data.should.haveOwnProperty('jsonrpc')
r.data.should.haveOwnProperty('error')
r.data['jsonrpc'].should.equal('2.0')
})
})
it('reverts properly', async () => {
const result: AxiosResponse = await request(client, {
id: 1,
jsonrpc: '2.0',
method: revertMethod,
})
result.status.should.equal(200)
result.data.should.haveOwnProperty('id')
result.data.should.haveOwnProperty('jsonrpc')
result.data.should.haveOwnProperty('error')
result.data['error'].should.haveOwnProperty('message')
result.data['error'].should.haveOwnProperty('code')
result.data['error']['message'].should.equal(
JSONRPC_ERRORS.REVERT_ERROR.message
)
result.data['error']['code'].should.equal(
JSONRPC_ERRORS.REVERT_ERROR.code
)
result.data['jsonrpc'].should.equal('2.0')
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const results: AxiosResponse[] = await Promise.all(
Array.from(defaultSupportedMethods).map((x) =>
request(client, { id: 1, jsonrpc: '2.0', method: x })
)
)
results.forEach((r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data['id'].should.equal(1)
r.data.should.haveOwnProperty('jsonrpc')
r.data['jsonrpc'].should.equal('2.0')
r.data.should.haveOwnProperty('result')
r.data['result'].should.equal(dummyResponse)
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(x) =>
request(client, { id: 1, jsonrpc: '2.0', method: x })
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data['id'].should.equal(1)
r.data.should.haveOwnProperty('jsonrpc')
r.data['jsonrpc'].should.equal('2.0')
r.data.should.haveOwnProperty('result')
r.data['result'].should.equal(dummyResponse)
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const results: AxiosResponse[] = await Promise.all(
getBadPayloads().map((x) => request(client, x))
)
results.forEach((r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data.should.haveOwnProperty('jsonrpc')
r.data.should.haveOwnProperty('error')
r.data['jsonrpc'].should.equal('2.0')
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(x) => request(client, x)
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(r) => {
r.status.should.equal(200)
r.data.should.haveOwnProperty('id')
r.data.should.haveOwnProperty('jsonrpc')
r.data.should.haveOwnProperty('error')
r.data['jsonrpc'].should.equal('2.0')
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const result: AxiosResponse = await request(client, {
id: 1,
jsonrpc: '2.0',
method: revertMethod,
})
result.status.should.equal(200)
result.data.should.haveOwnProperty('id')
result.data.should.haveOwnProperty('jsonrpc')
result.data.should.haveOwnProperty('error')
result.data['error'].should.haveOwnProperty('message')
result.data['error'].should.haveOwnProperty('code')
result.data['error']['message'].should.equal(
JSONRPC_ERRORS.REVERT_ERROR.message
)
result.data['error']['code'].should.equal(
JSONRPC_ERRORS.REVERT_ERROR.code
)
result.data['jsonrpc'].should.equal('2.0')
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
() => {
it('should work for valid requests & methods', async () => {
const batchRequest = Array.from(
defaultSupportedMethods
).map((method, id) => ({ jsonrpc: '2.0', id, method }))
const result: AxiosResponse = await request(client, batchRequest)
result.status.should.equal(200)
const results = result.data
results.forEach((r, id) => {
r.should.haveOwnProperty('id')
r['id'].should.equal(id)
r.should.haveOwnProperty('jsonrpc')
r['jsonrpc'].should.equal('2.0')
r.should.haveOwnProperty('result')
r['result'].should.equal(dummyResponse)
})
})
it('should fail on bad format or for valid requests & methods', async () => {
const result: AxiosResponse = await request(client, getBadPayloads())
result.status.should.equal(200)
const results = result.data
results.forEach((r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['jsonrpc'].should.equal('2.0')
})
})
it('should not allow batches of batches', async () => {
const batchOfBatches = Array.from(
defaultSupportedMethods
).map((method, id) => [{ jsonrpc: '2.0', id, method }])
const result: AxiosResponse = await request(client, batchOfBatches)
result.status.should.equal(200)
const results = result.data
results.forEach((r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['error'].should.haveOwnProperty('message')
r['error'].should.haveOwnProperty('code')
r['error']['message'].should.equal(
JSONRPC_ERRORS.INVALID_REQUEST.message
)
r['error']['code'].should.equal(JSONRPC_ERRORS.INVALID_REQUEST.code)
r['jsonrpc'].should.equal('2.0')
})
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const batchRequest = Array.from(
defaultSupportedMethods
).map((method, id) => ({ jsonrpc: '2.0', id, method }))
const result: AxiosResponse = await request(client, batchRequest)
result.status.should.equal(200)
const results = result.data
results.forEach((r, id) => {
r.should.haveOwnProperty('id')
r['id'].should.equal(id)
r.should.haveOwnProperty('jsonrpc')
r['jsonrpc'].should.equal('2.0')
r.should.haveOwnProperty('result')
r['result'].should.equal(dummyResponse)
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(method, id) => ({ jsonrpc: '2.0', id, method })
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(r, id) => {
r.should.haveOwnProperty('id')
r['id'].should.equal(id)
r.should.haveOwnProperty('jsonrpc')
r['jsonrpc'].should.equal('2.0')
r.should.haveOwnProperty('result')
r['result'].should.equal(dummyResponse)
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const result: AxiosResponse = await request(client, getBadPayloads())
result.status.should.equal(200)
const results = result.data
results.forEach((r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['jsonrpc'].should.equal('2.0')
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['jsonrpc'].should.equal('2.0')
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const batchOfBatches = Array.from(
defaultSupportedMethods
).map((method, id) => [{ jsonrpc: '2.0', id, method }])
const result: AxiosResponse = await request(client, batchOfBatches)
result.status.should.equal(200)
const results = result.data
results.forEach((r) => {
r.should.haveOwnProperty('id')
r.should.haveOwnProperty('jsonrpc')
r.should.haveOwnProperty('error')
r['error'].should.haveOwnProperty('message')
r['error'].should.haveOwnProperty('code')
r['error']['message'].should.equal(
JSONRPC_ERRORS.INVALID_REQUEST.message
)
r['error']['code'].should.equal(JSONRPC_ERRORS.INVALID_REQUEST.code)
r['jsonrpc'].should.equal('2.0')
})
}
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
ArrowFunction
|
(method, id) => [{ jsonrpc: '2.0', id, method }]
|
Genysys/optimism-monorepo
|
packages/rollup-full-node/test/app/fullnode-rpc-server.spec.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.