type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
ArrowFunction |
() => {
const onExecute: jest.Mock = jest.fn();
ktpTree.addNode({ ...keytipB, onExecute, hasDynamicChildren: true }, uniqueIdB);
ktpTree.currentKeytip = ktpTree.root;
layerValue.processInput('b');
// Node B's onExecute should be called
expect(onExecute).toBeCalled();
// There is no more buffer in the sequence
expect(layerValue.getCurrentSequence().length).toEqual(0);
// We haven't exited keytip mode (current keytip is set to the matched keytip)
expect(ktpTree.currentKeytip.id).toEqual(keytipIdB);
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
// Make E2 a persisted node
const nodeE2 = ktpTree.getNode(keytipIdE2)!;
nodeE2.persisted = true;
nodeE2.onExecute = jest.fn();
ktpTree.currentKeytip = ktpTree.root;
layerValue.processInput('e');
// Only E1 should be visible
const visibleLayerKtps: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleLayerKtps).toHaveLength(1);
expect(visibleLayerKtps[0].content).toEqual('E1');
layerValue.processInput('2');
// E2 should be triggered
expect(nodeE2.onExecute).toBeCalled();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
// Create layer
it('shows the defined keytips and hides all others', () => {
ktpMgr.keytips = {
[uniqueIdB]: { keytip: keytipB, uniqueID: uniqueIdB },
[uniqueIdC]: { keytip: keytipC, uniqueID: uniqueIdC },
[uniqueIdD]: { keytip: keytipD, uniqueID: uniqueIdD },
[uniqueIdE1]: { keytip: keytipE1, uniqueID: uniqueIdE1 },
[uniqueIdE2]: { keytip: keytipE2, uniqueID: uniqueIdE2 },
};
ktpLayer = mount(<KeytipLayerBase componentRef={layerRef} content="Alt Windows" />);
layerRef.current!.showKeytips([keytipIdB, keytipIdC]);
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(2);
expect(getKeytip(visibleKeytips, 'B')).toBeDefined();
expect(getKeytip(visibleKeytips, 'C')).toBeDefined();
});
it('should handle overflowSetSequence correctly', () => {
ktpMgr.keytips = {
[uniqueIdB]: {
keytip: {
...keytipB,
overflowSetSequence: ['x'],
},
uniqueID: uniqueIdB,
},
[uniqueIdC]: { keytip: keytipC, uniqueID: uniqueIdC },
[uniqueIdD]: { keytip: keytipD, uniqueID: uniqueIdD },
[uniqueIdE1]: { keytip: keytipE1, uniqueID: uniqueIdE1 },
[uniqueIdE2]: { keytip: keytipE2, uniqueID: uniqueIdE2 },
};
ktpLayer = mount(<KeytipLayerBase componentRef={layerRef} content="Alt Windows" />);
layerRef.current!.showKeytips(['ktp-x-b']);
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(1);
expect(getKeytip(visibleKeytips, 'B')).toBeDefined();
});
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
ktpMgr.keytips = {
[uniqueIdB]: { keytip: keytipB, uniqueID: uniqueIdB },
[uniqueIdC]: { keytip: keytipC, uniqueID: uniqueIdC },
[uniqueIdD]: { keytip: keytipD, uniqueID: uniqueIdD },
[uniqueIdE1]: { keytip: keytipE1, uniqueID: uniqueIdE1 },
[uniqueIdE2]: { keytip: keytipE2, uniqueID: uniqueIdE2 },
};
ktpLayer = mount(<KeytipLayerBase componentRef={layerRef} content="Alt Windows" />);
layerRef.current!.showKeytips([keytipIdB, keytipIdC]);
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(2);
expect(getKeytip(visibleKeytips, 'B')).toBeDefined();
expect(getKeytip(visibleKeytips, 'C')).toBeDefined();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
ktpMgr.keytips = {
[uniqueIdB]: {
keytip: {
...keytipB,
overflowSetSequence: ['x'],
},
uniqueID: uniqueIdB,
},
[uniqueIdC]: { keytip: keytipC, uniqueID: uniqueIdC },
[uniqueIdD]: { keytip: keytipD, uniqueID: uniqueIdD },
[uniqueIdE1]: { keytip: keytipE1, uniqueID: uniqueIdE1 },
[uniqueIdE2]: { keytip: keytipE2, uniqueID: uniqueIdE2 },
};
ktpLayer = mount(<KeytipLayerBase componentRef={layerRef} content="Alt Windows" />);
layerRef.current!.showKeytips(['ktp-x-b']);
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(1);
expect(getKeytip(visibleKeytips, 'B')).toBeDefined();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
beforeEach(() => {
jest.useFakeTimers();
ktpMgr.delayUpdatingKeytipChange = false;
ktpMgr.inKeytipMode = false;
// Add keytips to the manager
ktpMgr.keytips = {
[uniqueIdB]: { keytip: keytipB, uniqueID: uniqueIdB },
[uniqueIdC]: { keytip: keytipC, uniqueID: uniqueIdC },
[uniqueIdD]: { keytip: keytipD, uniqueID: uniqueIdD },
[uniqueIdE1]: { keytip: keytipE1, uniqueID: uniqueIdE1 },
[uniqueIdE2]: { keytip: keytipE2, uniqueID: uniqueIdE2 },
};
ktpMgr.persistedKeytips = { [uniqueIdG]: { keytip: keytipG, uniqueID: uniqueIdG } };
// Create layer
ktpLayer = mount(<KeytipLayerBase componentRef={layerRef} content="Alt Windows" />);
ktpTree = layerRef.current!.getKeytipTree();
});
afterEach(() => {
jest.useRealTimers();
});
it('keytipAdded event delay-shows a keytip if the current keytip is its parent', () => {
ktpTree.currentKeytip = ktpTree.getNode(keytipIdB);
// Add a child under B
ktpMgr.register({
content: 'X',
keySequences: ['b', 'x'],
});
jest.runAllTimers();
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(1);
expect(getKeytip(visibleKeytips, 'X')).toBeDefined();
});
// eslint-disable-next-line @fluentui/max-len
it('keytipAdded event does not show a keytip if the current keytip is its parent when delay updating and not in keytip mode', () => {
ktpMgr.delayUpdatingKeytipChange = true;
ktpTree.currentKeytip = ktpTree.getNode(keytipIdB);
// Add a child under B
ktpMgr.register({
content: 'X',
keySequences: ['b', 'x'],
});
jest.runAllTimers();
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(0);
expect(getKeytip(visibleKeytips, 'X')).toBeUndefined();
});
// eslint-disable-next-line @fluentui/max-len
it('keytipAdded event delay-shows a keytip if the current keytip is its parent when delay updating and in keytip mode', () => {
ktpMgr.delayUpdatingKeytipChange = true;
ktpMgr.inKeytipMode = true;
ktpTree.currentKeytip = ktpTree.getNode(keytipIdB);
// Add a child under B
ktpMgr.register({
content: 'X',
keySequences: ['b', 'x'],
});
jest.runAllTimers();
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(1);
expect(getKeytip(visibleKeytips, 'X')).toBeDefined();
});
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
jest.useFakeTimers();
ktpMgr.delayUpdatingKeytipChange = false;
ktpMgr.inKeytipMode = false;
// Add keytips to the manager
ktpMgr.keytips = {
[uniqueIdB]: { keytip: keytipB, uniqueID: uniqueIdB },
[uniqueIdC]: { keytip: keytipC, uniqueID: uniqueIdC },
[uniqueIdD]: { keytip: keytipD, uniqueID: uniqueIdD },
[uniqueIdE1]: { keytip: keytipE1, uniqueID: uniqueIdE1 },
[uniqueIdE2]: { keytip: keytipE2, uniqueID: uniqueIdE2 },
};
ktpMgr.persistedKeytips = { [uniqueIdG]: { keytip: keytipG, uniqueID: uniqueIdG } };
// Create layer
ktpLayer = mount(<KeytipLayerBase componentRef={layerRef} content="Alt Windows" />);
ktpTree = layerRef.current!.getKeytipTree();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
jest.useRealTimers();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
ktpTree.currentKeytip = ktpTree.getNode(keytipIdB);
// Add a child under B
ktpMgr.register({
content: 'X',
keySequences: ['b', 'x'],
});
jest.runAllTimers();
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(1);
expect(getKeytip(visibleKeytips, 'X')).toBeDefined();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
ktpMgr.delayUpdatingKeytipChange = true;
ktpTree.currentKeytip = ktpTree.getNode(keytipIdB);
// Add a child under B
ktpMgr.register({
content: 'X',
keySequences: ['b', 'x'],
});
jest.runAllTimers();
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(0);
expect(getKeytip(visibleKeytips, 'X')).toBeUndefined();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
ktpMgr.delayUpdatingKeytipChange = true;
ktpMgr.inKeytipMode = true;
ktpTree.currentKeytip = ktpTree.getNode(keytipIdB);
// Add a child under B
ktpMgr.register({
content: 'X',
keySequences: ['b', 'x'],
});
jest.runAllTimers();
const visibleKeytips: IKeytipProps[] = ktpLayer.state('visibleKeytips');
expect(visibleKeytips).toHaveLength(1);
expect(getKeytip(visibleKeytips, 'X')).toBeDefined();
} | Augani/fluentui | packages/react/src/components/KeytipLayer/KeytipLayer.test.tsx | TypeScript |
ArrowFunction |
() => {
const [visible, setVisible] = useState(false);
return (
<>
<Tool>
<Button type="primary" onClick={() | foxpage/foxpage-sdk-js | packages/foxpage-debug-portal/src/App.tsx | TypeScript |
ClassDeclaration | /**
* A component that formats all the data associated with a batch for display.
*/
@Component({
selector: 'batch',
templateUrl: './batch.component.html',
styleUrls: [
'./batch.component.scss',
'../../../styles/shared/_explorer-detail.scss'
],
providers: [Base64DecodePipe]
})
export class BatchComponent implements OnInit {
// data representing the batch
@Input() data: any = {};
// whether transaction data on this batch is shown as JSON
@Input() showDataAsJSON?: boolean;
// data stringified for Angular UI Ace to display
jsonData = '{}';
aceMode = 'json';
/**
* @param base64DecodePipe {Base64DecodePipe} -- used for decoding base64
* to ascii strings
*/
constructor(private base64DecodePipe: Base64DecodePipe) {}
ngOnInit(): void {
// format data for Angular UI Ace
this.jsonData = this.formatJSONData(this.data);
}
/**
* Formats batch data into a JSON string with proper indentation for display.
* @param transactionData - data representing a transaction within the batch
* @returns {string} formatted JSON string of the data
*/
formatJSONData(data: any) {
if (!data) data = {};
// format transactions within the batch data
if (data.transactions && this.showDataAsJSON) {
for (var txnIdx in data.transactions) {
data.transactions[txnIdx] =
this.formatTransactionData(data.transactions[txnIdx]);
}
}
return JSON.stringify(data, null, 2);
}
/**
* Formats information held in the payloads in a batch's transactions.
* @param transactionData - data representing a transaction within the batch
* @returns {object} formatted transaction data
*/
formatTransactionData(transactionData: any): string {
// decode transaction's payload from base64 into JSON
if (transactionData && transactionData.payload) {
transactionData.payload =
this.base64DecodePipe.transform(transactionData.payload);
try {
transactionData.payload = JSON.parse(transactionData.payload);
} catch(e) {}
}
return transactionData;
}
} | InfoScienceLabs/IoT-chain-Explorer | src/app/batches/batch/batch.component.ts | TypeScript |
MethodDeclaration |
ngOnInit(): void {
// format data for Angular UI Ace
this.jsonData = this.formatJSONData(this.data);
} | InfoScienceLabs/IoT-chain-Explorer | src/app/batches/batch/batch.component.ts | TypeScript |
MethodDeclaration | /**
* Formats batch data into a JSON string with proper indentation for display.
* @param transactionData - data representing a transaction within the batch
* @returns {string} formatted JSON string of the data
*/
formatJSONData(data: any) {
if (!data) data = {};
// format transactions within the batch data
if (data.transactions && this.showDataAsJSON) {
for (var txnIdx in data.transactions) {
data.transactions[txnIdx] =
this.formatTransactionData(data.transactions[txnIdx]);
}
}
return JSON.stringify(data, null, 2);
} | InfoScienceLabs/IoT-chain-Explorer | src/app/batches/batch/batch.component.ts | TypeScript |
MethodDeclaration | /**
* Formats information held in the payloads in a batch's transactions.
* @param transactionData - data representing a transaction within the batch
* @returns {object} formatted transaction data
*/
formatTransactionData(transactionData: any): string {
// decode transaction's payload from base64 into JSON
if (transactionData && transactionData.payload) {
transactionData.payload =
this.base64DecodePipe.transform(transactionData.payload);
try {
transactionData.payload = JSON.parse(transactionData.payload);
} catch(e) {}
}
return transactionData;
} | InfoScienceLabs/IoT-chain-Explorer | src/app/batches/batch/batch.component.ts | TypeScript |
ArrowFunction |
message => JSON.parse(message.payload.toString()) as Observation | 52North/eurofleets-dashboard | src/app/services/sta-mqtt-interface/sta-mqtt-interface.service.ts | TypeScript |
ArrowFunction |
observation => console.log(`Observation: ${observation.result}`) | 52North/eurofleets-dashboard | src/app/services/sta-mqtt-interface/sta-mqtt-interface.service.ts | TypeScript |
ClassDeclaration |
@Injectable({
providedIn: 'root'
})
export class StaMqttInterfaceService {
private mqttService: MqttService;
constructor() {
this.mqttService = new MqttService({
hostname: AppConfig.settings.sta.mqtt.hostname,
port: AppConfig.settings.sta.mqtt.port,
path: AppConfig.settings.sta.mqtt.path
});
}
public subscribeDatastreamObservations(
datasetId: string,
params?: StaFilter<ObservationSelectParams, ObservationExpandParams>
): Observable<Observation> {
// TODO: add filterung: $select=result,phenomenonTime
return this.mqttService.observe(`Datastreams(${datasetId})/Observations`).pipe(
map(message => JSON.parse(message.payload.toString()) as Observation),
// tap(observation => console.log(`Observation for ${datasetId} with result: ${JSON.stringify(observation, null, 2)}`))
);
}
public subscribeObservations(): Observable<Observation> {
return this.mqttService.observe(`Observations`).pipe(
map(message => JSON.parse(message.payload.toString()) as Observation),
tap(observation => console.log(`Observation: ${observation.result}`))
);
}
} | 52North/eurofleets-dashboard | src/app/services/sta-mqtt-interface/sta-mqtt-interface.service.ts | TypeScript |
MethodDeclaration |
public subscribeDatastreamObservations(
datasetId: string,
params?: StaFilter<ObservationSelectParams, ObservationExpandParams>
): Observable<Observation> {
// TODO: add filterung: $select=result,phenomenonTime
return this.mqttService.observe(`Datastreams(${datasetId})/Observations`).pipe(
map(message => JSON.parse(message.payload.toString()) as Observation),
// tap(observation => console.log(`Observation for ${datasetId} with result: ${JSON.stringify(observation, null, 2)}`))
);
} | 52North/eurofleets-dashboard | src/app/services/sta-mqtt-interface/sta-mqtt-interface.service.ts | TypeScript |
MethodDeclaration |
public subscribeObservations(): Observable<Observation> {
return this.mqttService.observe(`Observations`).pipe(
map(message => JSON.parse(message.payload.toString()) as Observation),
tap(observation => console.log(`Observation: ${observation.result}`))
);
} | 52North/eurofleets-dashboard | src/app/services/sta-mqtt-interface/sta-mqtt-interface.service.ts | TypeScript |
ClassDeclaration |
export default class ChatController extends Controller {
async index() {
const { ctx } = this;
try {
const socket: any = ctx.socket;
const message = ctx.args[0] || {};
const { roomId, receive } = message;
socket.broadcast.emit(roomId, {
...message,
target: roomId
});
socket.broadcast.emit(receive, {
...message,
target: receive
});
} catch (error) {
this.app.logger.error(error);
}
}
} | csjiabin/part-time-egg | app/io/controller/chat.ts | TypeScript |
MethodDeclaration |
async index() {
const { ctx } = this;
try {
const socket: any = ctx.socket;
const message = ctx.args[0] || {};
const { roomId, receive } = message;
socket.broadcast.emit(roomId, {
...message,
target: roomId
});
socket.broadcast.emit(receive, {
...message,
target: receive
});
} catch (error) {
this.app.logger.error(error);
}
} | csjiabin/part-time-egg | app/io/controller/chat.ts | TypeScript |
FunctionDeclaration |
function App() {
return (
<BrowserRouter>
<AuthContextProvider>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/rooms/new" component={NewRoom} />
<Route path="/rooms/:id" component={Room} />
<Route path="/admin/rooms/:id" component={AdminRoom} />
</Switch>
</AuthContextProvider>
</BrowserRouter>
);
} | AloisioFernandes/NLW6-Together-React | letmeask/src/App.tsx | TypeScript |
ClassDeclaration |
@Injectable()
export class VendorBillService {
options: any;
constructor(private http: Http) {
let token = localStorage.getItem('userToken');
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', token)
this.options = new RequestOptions({ headers: headers });
}
getVendorBillProducts(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
saveVendorBillPayment(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
deleteVendorBillPayment(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
saveVendorBill(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
getAllVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
getVendorBillPayments(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
deleteVendorBill(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
filterVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
getThisWeekVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
getThisMonthVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
}
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
getVendorBillProducts(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
saveVendorBillPayment(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
deleteVendorBillPayment(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
saveVendorBill(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
getAllVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
getVendorBillPayments(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
deleteVendorBill(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
filterVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
getThisWeekVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
MethodDeclaration |
getThisMonthVendorBills(url: string, input: any): any {
return this.http.post(url, input, this.options)
.map((response: Response) => response.json());
} | Wahap/Supplier.PL | src/app/layout/vendorBills/vendor-bill.service.ts | TypeScript |
ArrowFunction |
({ factory }: Pick<ts.TransformationContext, "factory">): Factory["create"] => (
params: Params,
): ts.VariableDeclaration => {
const node = factory.createVariableDeclaration(params.name, undefined, params.type, params.initializer);
return node;
} | Himenon/openapi-typescript-code-generator | src/internal/TsGenerator/factory/VariableDeclaration.ts | TypeScript |
ArrowFunction |
(
params: Params,
): ts.VariableDeclaration => {
const node = factory.createVariableDeclaration(params.name, undefined, params.type, params.initializer);
return node;
} | Himenon/openapi-typescript-code-generator | src/internal/TsGenerator/factory/VariableDeclaration.ts | TypeScript |
ArrowFunction |
(context: Pick<ts.TransformationContext, "factory">): Factory => {
return {
create: create(context),
};
} | Himenon/openapi-typescript-code-generator | src/internal/TsGenerator/factory/VariableDeclaration.ts | TypeScript |
InterfaceDeclaration |
export interface Params {
name: string | ts.BindingName;
type?: ts.TypeNode;
initializer?: ts.Expression;
} | Himenon/openapi-typescript-code-generator | src/internal/TsGenerator/factory/VariableDeclaration.ts | TypeScript |
InterfaceDeclaration |
export interface Factory {
create: (params: Params) => ts.VariableDeclaration;
} | Himenon/openapi-typescript-code-generator | src/internal/TsGenerator/factory/VariableDeclaration.ts | TypeScript |
InterfaceDeclaration |
export interface DecoratorTestStructure extends BaseTestStructure, NamedTestStructure {
isDecoratorFactory?: boolean;
arguments?: ExpressionTestStructure[];
} | 700software/ts-code-generator | src/tests/testHelpers/testStructures/general/DecoratorTestStructure.ts | TypeScript |
ArrowFunction |
(acc: { [keys: string]: Selectable<CandidateBackground_OutsideWorkExperience> }, field: Selectable<CandidateBackground_OutsideWorkExperience>) => {
acc[field._fieldName] = field;
return acc;
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
ClassDeclaration | /**
* This class represents the entity "CandidateBackground_OutsideWorkExperience" of service "SFOData".
*/
export class CandidateBackground_OutsideWorkExperience extends Entity implements CandidateBackground_OutsideWorkExperienceType {
/**
* Technical entity name for CandidateBackground_OutsideWorkExperience.
*/
static _entityName = 'CandidateBackground_OutsideWorkExperience';
/**
* @deprecated Since v1.0.1 Use [[_defaultServicePath]] instead.
* Technical service name for CandidateBackground_OutsideWorkExperience.
*/
static _serviceName = 'SFOData';
/**
* Default url path for the according service.
*/
static _defaultServicePath = 'VALUE_IS_UNDEFINED';
/**
* Background Element Id.
*/
backgroundElementId!: BigNumber;
/**
* Background Order Position.
*/
bgOrderPos!: BigNumber;
/**
* Type of Business.
*/
businessType!: string;
/**
* Candidate Id.
*/
candidateId!: BigNumber;
/**
* Country.
*/
country!: string;
/**
* Company Name.
*/
employer!: string;
/**
* End Date.
*/
endDate!: Moment;
/**
* Last Modified Date.
*/
lastModifiedDateTime!: Moment;
/**
* Present Employer.
*/
presentEmployer!: string;
/**
* From Date.
*/
startDate!: Moment;
/**
* Title.
*/
startTitle!: string;
/**
* One-to-one navigation property to the [[PicklistOption]] entity.
*/
businessTypeNav!: PicklistOption;
/**
* One-to-one navigation property to the [[Candidate]] entity.
*/
candidate!: Candidate;
/**
* One-to-one navigation property to the [[PicklistOption]] entity.
*/
countryNav!: PicklistOption;
/**
* One-to-one navigation property to the [[PicklistOption]] entity.
*/
presentEmployerNav!: PicklistOption;
/**
* Returns an entity builder to construct instances `CandidateBackground_OutsideWorkExperience`.
* @returns A builder that constructs instances of entity type `CandidateBackground_OutsideWorkExperience`.
*/
static builder(): EntityBuilderType<CandidateBackground_OutsideWorkExperience, CandidateBackground_OutsideWorkExperienceTypeForceMandatory> {
return Entity.entityBuilder(CandidateBackground_OutsideWorkExperience);
}
/**
* Returns a request builder to construct requests for operations on the `CandidateBackground_OutsideWorkExperience` entity type.
* @returns A `CandidateBackground_OutsideWorkExperience` request builder.
*/
static requestBuilder(): CandidateBackground_OutsideWorkExperienceRequestBuilder {
return new CandidateBackground_OutsideWorkExperienceRequestBuilder();
}
/**
* Returns a selectable object that allows the selection of custom field in a get request for the entity `CandidateBackground_OutsideWorkExperience`.
* @param fieldName Name of the custom field to select
* @returns A builder that constructs instances of entity type `CandidateBackground_OutsideWorkExperience`.
*/
static customField(fieldName: string): CustomField<CandidateBackground_OutsideWorkExperience> {
return Entity.customFieldSelector(fieldName, CandidateBackground_OutsideWorkExperience);
}
/**
* Overwrites the default toJSON method so that all instance variables as well as all custom fields of the entity are returned.
* @returns An object containing all instance variables + custom fields.
*/
toJSON(): { [key: string]: any } {
return { ...this, ...this._customFields };
}
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
InterfaceDeclaration |
export interface CandidateBackground_OutsideWorkExperienceType {
backgroundElementId: BigNumber;
bgOrderPos: BigNumber;
businessType: string;
candidateId: BigNumber;
country: string;
employer: string;
endDate: Moment;
lastModifiedDateTime: Moment;
presentEmployer: string;
startDate: Moment;
startTitle: string;
businessTypeNav: PicklistOptionType;
candidate: CandidateType;
countryNav: PicklistOptionType;
presentEmployerNav: PicklistOptionType;
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
InterfaceDeclaration |
export interface CandidateBackground_OutsideWorkExperienceTypeForceMandatory {
backgroundElementId: BigNumber;
bgOrderPos: BigNumber;
businessType: string;
candidateId: BigNumber;
country: string;
employer: string;
endDate: Moment;
lastModifiedDateTime: Moment;
presentEmployer: string;
startDate: Moment;
startTitle: string;
businessTypeNav: PicklistOptionType;
candidate: CandidateType;
countryNav: PicklistOptionType;
presentEmployerNav: PicklistOptionType;
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
MethodDeclaration | /**
* Returns an entity builder to construct instances `CandidateBackground_OutsideWorkExperience`.
* @returns A builder that constructs instances of entity type `CandidateBackground_OutsideWorkExperience`.
*/
static builder(): EntityBuilderType<CandidateBackground_OutsideWorkExperience, CandidateBackground_OutsideWorkExperienceTypeForceMandatory> {
return Entity.entityBuilder(CandidateBackground_OutsideWorkExperience);
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
MethodDeclaration | /**
* Returns a request builder to construct requests for operations on the `CandidateBackground_OutsideWorkExperience` entity type.
* @returns A `CandidateBackground_OutsideWorkExperience` request builder.
*/
static requestBuilder(): CandidateBackground_OutsideWorkExperienceRequestBuilder {
return new CandidateBackground_OutsideWorkExperienceRequestBuilder();
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
MethodDeclaration | /**
* Returns a selectable object that allows the selection of custom field in a get request for the entity `CandidateBackground_OutsideWorkExperience`.
* @param fieldName Name of the custom field to select
* @returns A builder that constructs instances of entity type `CandidateBackground_OutsideWorkExperience`.
*/
static customField(fieldName: string): CustomField<CandidateBackground_OutsideWorkExperience> {
return Entity.customFieldSelector(fieldName, CandidateBackground_OutsideWorkExperience);
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
MethodDeclaration | /**
* Overwrites the default toJSON method so that all instance variables as well as all custom fields of the entity are returned.
* @returns An object containing all instance variables + custom fields.
*/
toJSON(): { [key: string]: any } {
return { ...this, ...this._customFields };
} | robypag/sdk-gen-sfsf | src/odata-client/sfo-data-service/CandidateBackground_OutsideWorkExperience.ts | TypeScript |
ClassDeclaration |
@Module({
controllers: [MemesController],
providers: [MemesService],
imports: [ConfigModule],
})
export class MemesModule {} | kamilwronka/memes-service | src/memes/memes.module.ts | TypeScript |
FunctionDeclaration |
function triggerAbortedSignalAfterNumCalls(maxCalls: number): AbortSignal {
let count = 0;
const abortSignal: AbortSignal = {
get aborted(): boolean {
++count;
if (count >= maxCalls) {
return true;
}
return false;
},
addEventListener: () => {},
removeEventListener: () => {},
onabort: () => {},
dispatchEvent: () => true
};
return abortSignal;
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
let checkpoints: Checkpoint[] = [
{
fullyQualifiedNamespace: "not-used-for-this-test",
consumerGroup: "not-used-for-this-test",
eventHubName: "not-used-for-this-test",
offset: 1009,
sequenceNumber: 1010,
partitionId: "0"
},
{
fullyQualifiedNamespace: "not-used-for-this-test",
consumerGroup: "not-used-for-this-test",
eventHubName: "not-used-for-this-test",
// this caused a bug for us before - it's a perfectly valid offset
// but we were thrown off by its falsy-ness. (actually it was
// sequence number before but the concept is the same)
offset: 0,
sequenceNumber: 0,
partitionId: "1"
}
];
const checkpointStore: CheckpointStore = {
claimOwnership: async () => {
return [];
},
listCheckpoints: async () => {
return checkpoints;
},
listOwnership: async () => {
return [];
},
updateCheckpoint: async () => {}
};
// we're not actually going to start anything here so there's nothing
// to stop
const processor = new EventProcessor(
EventHubClient.defaultConsumerGroupName,
client,
{
processEvents: async () => {},
processError: async () => {}
},
checkpointStore,
{
maxBatchSize: 1,
maxWaitTimeInSeconds: 1
}
);
// checkpoint is available for partition 0
let eventPosition = await processor["_getStartingPosition"]("0");
eventPosition!.offset!.should.equal(1009);
should.not.exist(eventPosition!.sequenceNumber);
//checkpoint is available for partition 1
eventPosition = await processor["_getStartingPosition"]("1");
eventPosition!.offset!.should.equal(0);
should.not.exist(eventPosition!.sequenceNumber);
// no checkpoint available for partition 2
eventPosition = await processor["_getStartingPosition"]("2");
should.not.exist(eventPosition);
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
return [];
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
return checkpoints;
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
() => {
let eventProcessor: EventProcessor;
let userCallback: (() => void) | undefined;
let errorFromCallback: Error | undefined;
let contextFromCallback: PartitionContext | undefined;
beforeEach(() => {
userCallback = undefined;
errorFromCallback = undefined;
contextFromCallback = undefined;
// note: we're not starting this event processor so there's nothing to stop()
// it's only here so we can call a few private methods on it.
eventProcessor = new EventProcessor(
EventHubClient.defaultConsumerGroupName,
client,
{
processEvents: async () => {},
processError: async (err, context) => {
// simulate the user messing up and accidentally throwing an error
// we should just log it and not kill anything.
errorFromCallback = err;
contextFromCallback = context;
if (userCallback) {
userCallback();
}
}
},
new InMemoryCheckpointStore(),
defaultOptions
);
});
it("error thrown from user's processError handler", async () => {
// the user's error handler will throw an error - won't escape from this function
userCallback = () => {
throw new Error("Error thrown from the user's error handler");
};
await eventProcessor["_handleSubscriptionError"](new Error("test error"));
errorFromCallback!.message.should.equal("test error");
contextFromCallback!.partitionId.should.equal("");
});
it("non-useful errors are filtered out", async () => {
// the user's error handler will throw an error - won't escape from this function
await eventProcessor["_handleSubscriptionError"](new AbortError("test error"));
// we don't call the user's handler for abort errors
should.not.exist(errorFromCallback);
should.not.exist(contextFromCallback);
});
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
() => {
userCallback = undefined;
errorFromCallback = undefined;
contextFromCallback = undefined;
// note: we're not starting this event processor so there's nothing to stop()
// it's only here so we can call a few private methods on it.
eventProcessor = new EventProcessor(
EventHubClient.defaultConsumerGroupName,
client,
{
processEvents: async () => {},
processError: async (err, context) => {
// simulate the user messing up and accidentally throwing an error
// we should just log it and not kill anything.
errorFromCallback = err;
contextFromCallback = context;
if (userCallback) {
userCallback();
}
}
},
new InMemoryCheckpointStore(),
defaultOptions
);
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async (err, context) => {
// simulate the user messing up and accidentally throwing an error
// we should just log it and not kill anything.
errorFromCallback = err;
contextFromCallback = context;
if (userCallback) {
userCallback();
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
// the user's error handler will throw an error - won't escape from this function
userCallback = () => {
throw new Error("Error thrown from the user's error handler");
};
await eventProcessor["_handleSubscriptionError"](new Error("test error"));
errorFromCallback!.message.should.equal("test error");
contextFromCallback!.partitionId.should.equal("");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
() => {
throw new Error("Error thrown from the user's error handler");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
// the user's error handler will throw an error - won't escape from this function
await eventProcessor["_handleSubscriptionError"](new AbortError("test error"));
// we don't call the user's handler for abort errors
should.not.exist(errorFromCallback);
should.not.exist(contextFromCallback);
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
const checkpointStore = {
claimOwnershipCalled: false,
// the important thing is that the EventProcessor won't be able to claim
// any partitions, causing it to go down the "I tried but failed" path.
async claimOwnership(_: PartitionOwnership[]): Promise<PartitionOwnership[]> {
checkpointStore.claimOwnershipCalled = true;
return [];
},
// (these aren't used for this test)
async listOwnership(): Promise<PartitionOwnership[]> {
return [];
},
async updateCheckpoint(): Promise<void> {},
async listCheckpoints(): Promise<Checkpoint[]> {
return [];
}
};
const pumpManager = {
createPumpCalled: false,
async createPump() {
pumpManager.createPumpCalled = true;
},
async removeAllPumps() {}
};
const eventProcessor = new EventProcessor(
EventHubClient.defaultConsumerGroupName,
client,
{
processEvents: async () => {},
processError: async () => {}
},
checkpointStore,
{
...defaultOptions,
pumpManager: pumpManager
}
);
await eventProcessor["_claimOwnership"]({
consumerGroup: "cgname",
eventHubName: "ehname",
fullyQualifiedNamespace: "fqdn",
ownerId: "owner",
partitionId: "0"
});
// when we fail to claim a partition we should _definitely_
// not attempt to start a pump.
pumpManager.createPumpCalled.should.be.false;
// we'll attempt to claim a partition (but won't succeed)
checkpointStore.claimOwnershipCalled.should.be.true;
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
const commonFields = {
fullyQualifiedNamespace: "irrelevant namespace",
eventHubName: "irrelevant eventhub name",
consumerGroup: "irrelevant consumer group"
};
const handlers = new FakeSubscriptionEventHandlers();
const checkpointStore = new InMemoryCheckpointStore();
const originalClaimedPartitions = await checkpointStore.claimOwnership([
// abandoned claim
{ ...commonFields, partitionId: "1001", ownerId: "", etag: "abandoned etag" },
// normally owned claim
{ ...commonFields, partitionId: "1002", ownerId: "owned partition", etag: "owned etag" }
// 1003 - completely unowned
]);
originalClaimedPartitions.sort((a, b) => a.partitionId.localeCompare(b.partitionId));
const fakeEventHubClient = sinon.createStubInstance(EventHubClient);
const partitionIds = ["1001", "1002", "1003"];
fakeEventHubClient.getPartitionIds.resolves(partitionIds);
sinon.replaceGetter(fakeEventHubClient, "eventHubName", () => commonFields.eventHubName);
sinon.replaceGetter(
fakeEventHubClient,
"fullyQualifiedNamespace",
() => commonFields.fullyQualifiedNamespace
);
const ep = new EventProcessor(
commonFields.consumerGroup,
fakeEventHubClient as any,
handlers,
checkpointStore,
{
maxBatchSize: 1,
loopIntervalInMs: 1,
maxWaitTimeInSeconds: 1,
pumpManager: {
async createPump() {},
async removeAllPumps(): Promise<void> {}
}
}
);
// allow three iterations through the loop - one for each partition that
// we expect to be claimed
//
// we'll let one more go through just to make sure we're not going to
// pick up an extra surprise partition
//
// This particular behavior is really specific to the FairPartitionLoadBalancer but that's okay for now.
const numTimesAbortedIsCheckedInLoop = 3;
await ep["_runLoopWithLoadBalancing"](
ep["_processingTarget"] as PartitionLoadBalancer,
triggerAbortedSignalAfterNumCalls(partitionIds.length * numTimesAbortedIsCheckedInLoop)
);
handlers.errors.should.be.empty;
const currentOwnerships = await checkpointStore.listOwnership(
commonFields.fullyQualifiedNamespace,
commonFields.eventHubName,
commonFields.consumerGroup
);
currentOwnerships.sort((a, b) => a.partitionId.localeCompare(b.partitionId));
currentOwnerships.should.deep.equal([
{
...commonFields,
partitionId: "1001",
ownerId: ep.id,
etag: currentOwnerships[0].etag,
lastModifiedTimeInMs: currentOwnerships[0].lastModifiedTimeInMs
},
// 1002 is not going to be claimed since it's already owned so it should be untouched
originalClaimedPartitions[1],
{
...commonFields,
partitionId: "1003",
ownerId: ep.id,
etag: currentOwnerships[2].etag,
lastModifiedTimeInMs: currentOwnerships[2].lastModifiedTimeInMs
}
]);
// now let's "unclaim" everything by stopping our event processor
await ep.stop();
// sanity check - we were previously modifying the original instances
// in place which...isn't right.
currentOwnerships.should.deep.equal([
{
...commonFields,
partitionId: "1001",
ownerId: ep.id,
etag: currentOwnerships[0].etag,
lastModifiedTimeInMs: currentOwnerships[0].lastModifiedTimeInMs
},
// 1002 is not going to be claimed since it's already owned so it should be untouched
originalClaimedPartitions[1],
{
...commonFields,
partitionId: "1003",
ownerId: ep.id,
etag: currentOwnerships[2].etag,
lastModifiedTimeInMs: currentOwnerships[2].lastModifiedTimeInMs
}
]);
const ownershipsAfterStop = await checkpointStore.listOwnership(
commonFields.fullyQualifiedNamespace,
commonFields.eventHubName,
commonFields.consumerGroup
);
ownershipsAfterStop.sort((a, b) => a.partitionId.localeCompare(b.partitionId));
ownershipsAfterStop.should.deep.equal([
{
...commonFields,
partitionId: "1001",
ownerId: "",
etag: ownershipsAfterStop[0].etag,
lastModifiedTimeInMs: ownershipsAfterStop[0].lastModifiedTimeInMs
},
// 1002 is not going to be claimed since it's already owned so it should be untouched
originalClaimedPartitions[1],
{
...commonFields,
partitionId: "1003",
ownerId: "",
etag: ownershipsAfterStop[2].etag,
lastModifiedTimeInMs: ownershipsAfterStop[2].lastModifiedTimeInMs
}
]);
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
(a, b) => a.partitionId.localeCompare(b.partitionId) | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
() => commonFields.eventHubName | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
() => commonFields.fullyQualifiedNamespace | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
const errors = [];
const faultyCheckpointStore: CheckpointStore = {
listOwnership: async () => [],
claimOwnership: async () => {
throw new Error("Some random failure!");
},
updateCheckpoint: async () => {},
listCheckpoints: async () => []
};
const eventProcessor = new EventProcessor(
EventHubClient.defaultConsumerGroupName,
client,
{
processEvents: async () => {},
processError: async (err, _) => {
errors.push(err);
}
},
faultyCheckpointStore,
{
...defaultOptions,
processingTarget: new GreedyPartitionLoadBalancer(["0"])
}
);
// claimOwnership() calls that fail in the runloop of eventProcessor
// will get directed to the user's processError handler.
eventProcessor.start();
try {
await loopUntil({
name: "waiting for checkpoint store errors to show up",
timeBetweenRunsMs: 1000,
maxTimes: 30,
until: async () => errors.length !== 0
});
errors.length.should.equal(1);
} finally {
// this will also fail - we "abandon" all claimed partitions at
// when a processor is stopped (which requires us to claim them
// with an empty owner ID).
//
// Note that this one gets thrown directly from stop(), rather
// than reporting to processError() since we have a direct
// point of contact with the user.
await eventProcessor.stop().should.be.rejectedWith(/Some random failure!/);
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => [] | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
throw new Error("Some random failure!");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async (err, _) => {
errors.push(err);
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => errors.length !== 0 | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
const errors = new Set<Error>();
const eventProcessor = new EventProcessor(
EventHubClient.defaultConsumerGroupName,
client,
{
processClose: async () => {
throw new Error("processClose() error");
},
processEvents: async () => {
throw new Error("processEvents() error");
},
processInitialize: async () => {
throw new Error("processInitialize() error");
},
processError: async (err, _) => {
errors.add(err);
throw new Error("These are logged but ignored");
}
},
new InMemoryCheckpointStore(),
{
...defaultOptions,
processingTarget: new GreedyPartitionLoadBalancer(["0"])
}
);
// errors that occur within the user's own event handlers will get
// routed to their processError() handler
eventProcessor.start();
try {
await loopUntil({
name: "waiting for errors thrown from user's handlers",
timeBetweenRunsMs: 1000,
maxTimes: 30,
until: async () => errors.size >= 3
});
const messages = [...errors].map((e) => e.message);
messages.sort();
messages.should.deep.equal([
"processClose() error",
"processEvents() error",
"processInitialize() error"
]);
} finally {
await eventProcessor.stop();
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
throw new Error("processClose() error");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
throw new Error("processEvents() error");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
throw new Error("processInitialize() error");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async (err, _) => {
errors.add(err);
throw new Error("These are logged but ignored");
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => errors.size >= 3 | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
(e) => e.message | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async (context) => context.setStartingPosition(EventPosition.latest()) | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async (context) => {
didPartitionProcessorStart = true;
context.setStartingPosition(EventPosition.latest());
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async (event, context) => {} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
(id) => checkpointMap.set(id, []) | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
const checkpointStore = new InMemoryCheckpointStore();
const allObjects = new Set();
const assertUnique = (...objects: any[]) => {
const size = allObjects.size;
for (const obj of objects) {
allObjects.add(obj);
size.should.be.lessThan(allObjects.size);
}
};
const basicProperties = {
consumerGroup: "initial consumer group",
eventHubName: "initial event hub name",
fullyQualifiedNamespace: "initial fully qualified namespace"
};
const originalPartitionOwnership = {
...basicProperties,
ownerId: "initial owner ID",
partitionId: "1001"
};
const copyOfPartitionOwnership = {
...originalPartitionOwnership
};
assertUnique(originalPartitionOwnership);
for (let i = 0; i < 2; ++i) {
const ownerships = await checkpointStore.claimOwnership([originalPartitionOwnership]);
// second sanity check - we were also modifying the input parameter
// (which was also bad)
copyOfPartitionOwnership.should.deep.equal(originalPartitionOwnership);
assertUnique(...ownerships);
}
for (let i = 0; i < 2; ++i) {
const ownerships = await checkpointStore.listOwnership(
basicProperties.fullyQualifiedNamespace,
basicProperties.eventHubName,
basicProperties.consumerGroup
);
assertUnique(...ownerships);
}
const originalCheckpoint: Checkpoint = {
...basicProperties,
sequenceNumber: 1,
partitionId: "1",
offset: 101
};
const copyOfOriginalCheckpoint = {
...originalCheckpoint
};
await checkpointStore.updateCheckpoint(originalCheckpoint);
// checking that we don't modify input parameters
copyOfOriginalCheckpoint.should.deep.equal(originalCheckpoint);
for (let i = 0; i < 2; ++i) {
const checkpoints = await checkpointStore.listCheckpoints(
basicProperties.fullyQualifiedNamespace,
basicProperties.eventHubName,
basicProperties.consumerGroup
);
assertUnique(...checkpoints);
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
(...objects: any[]) => {
const size = allObjects.size;
for (const obj of objects) {
allObjects.add(obj);
size.should.be.lessThan(allObjects.size);
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
(id) => partitionResultsMap.set(id, { events: [], initialized: false }) | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
(event) => event.body | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => partitionOwnershipArr.size === partitionIds.length | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => {
// Ensure the partition ownerships are balanced.
const eventProcessorIds = Object.keys(claimedPartitionsMap);
// There are 2 processors, so we should see 2 entries.
if (eventProcessorIds.length !== 2) {
return false;
}
const aProcessorPartitions = claimedPartitionsMap[eventProcessorIds[0]];
const bProcessorPartitions = claimedPartitionsMap[eventProcessorIds[1]];
// The delta between number of partitions each processor owns can't be more than 1.
if (Math.abs(aProcessorPartitions.size - bProcessorPartitions.size) > 1) {
return false;
}
// All partitions must be claimed.
return aProcessorPartitions.size + bProcessorPartitions.size === partitionIds.length;
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ArrowFunction |
async () => thrashAfterSettling | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ClassDeclaration |
class FooPartitionProcessor {
async processInitialize(context: InitializationContext) {
context.setStartingPosition(EventPosition.earliest());
}
async processEvents(events: ReceivedEventData[], context: PartitionContext) {
processedAtLeastOneEvent.add(context.partitionId);
!partionCount[context.partitionId]
? (partionCount[context.partitionId] = 1)
: partionCount[context.partitionId]++;
const existingEvents = checkpointMap.get(context.partitionId)!;
for (const event of events) {
debug("Received event: '%s' from partition: '%s'", event.body, context.partitionId);
if (partionCount[context.partitionId] <= 50) {
checkpointSequenceNumbers.set(context.partitionId, event.sequenceNumber);
await context.updateCheckpoint(event);
existingEvents.push(event);
}
}
}
async processError(err: Error) {
didError = true;
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ClassDeclaration | // The partitionProcess will need to add events to the partitionResultsMap as they are received
class FooPartitionProcessor implements Required<SubscriptionEventHandlers> {
async processInitialize(context: InitializationContext) {
loggerForTest(`processInitialize(${context.partitionId})`);
partitionResultsMap.get(context.partitionId)!.initialized = true;
context.setStartingPosition(EventPosition.earliest());
}
async processClose(reason: CloseReason, context: PartitionContext) {
loggerForTest(`processClose(${context.partitionId})`);
partitionResultsMap.get(context.partitionId)!.closeReason = reason;
}
async processEvents(events: ReceivedEventData[], context: PartitionContext) {
partitionOwnershipArr.add(context.partitionId);
const existingEvents = partitionResultsMap.get(context.partitionId)!.events;
existingEvents.push(...events.map((event) => event.body));
}
async processError(err: Error, context: PartitionContext) {
loggerForTest(`processError(${context.partitionId})`);
didError = true;
errorName = err.name;
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ClassDeclaration | // The partitionProcess will need to add events to the partitionResultsMap as they are received
class FooPartitionProcessor {
async processInitialization(context: InitializationContext) {
context.setStartingPosition(EventPosition.earliest());
}
async processEvents(events: ReceivedEventData[], context: PartitionContext) {
partitionOwnershipArr.add(context.partitionId);
}
async processError() {
didError = true;
}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
ClassDeclaration |
class SimpleEventProcessor implements SubscriptionEventHandlers {
async processInitialization(context: InitializationContext) {
context.setStartingPosition(EventPosition.latest());
}
async processEvents(events: ReceivedEventData[], context: PartitionContext) {
partitionIdsSet.add(context.partitionId);
lastEnqueuedEventPropertiesMap.set(
context.partitionId,
context.lastEnqueuedEventProperties!
);
}
async processError(err: Error, context: PartitionContext) {}
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration | // the important thing is that the EventProcessor won't be able to claim
// any partitions, causing it to go down the "I tried but failed" path.
async claimOwnership(_: PartitionOwnership[]): Promise<PartitionOwnership[]> {
checkpointStore.claimOwnershipCalled = true;
return [];
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration | // (these aren't used for this test)
async listOwnership(): Promise<PartitionOwnership[]> {
return [];
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration |
async updateCheckpoint(): Promise<void> {} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration |
async listCheckpoints(): Promise<Checkpoint[]> {
return [];
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration |
async createPump() {
pumpManager.createPumpCalled = true;
} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration |
async removeAllPumps() {} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration |
async createPump() {} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
MethodDeclaration |
async removeAllPumps(): Promise<void> {} | qiaozha/azure-sdk-for-js | sdk/eventhub/event-hubs/test/eventProcessor.spec.ts | TypeScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.