How to use paramsName method in Playwright Internal

Best JavaScript code snippet using playwright-internal

scriptListConfigNew.js

Source:scriptListConfigNew.js Github

copy

Full Screen

1define([], function () {2 return {3 "scripts": {4 "plotPublishPrice": {5 "reportName": "Гистограмма цены выставленных товаров",6 "axis": {7 "xAxis": "Логарифм по основанию 10 от цены выставленного товара",8 "yAxis": "Количество выставленных товаров из данного ценового интервала"9 },10 "return": {11 "type": "plot",12 "fieldLabel": {13 "id": "id",14 "x": "Логарифм по основанию 10 от цены выставленного товара",15 "y": "Количество выставленных товаров из данного ценового интервала"16 },17 "fields": {18 "label": {19 "id": "id",20 "x": "Логарифм по основанию 10 от цены выставленного товара",21 "y": "Количество выставленных товаров из данного ценового интервала"22 },23 'type':{24 "id": "int",25 "x": "float",26 "y": "int"27 }28 },29 30 "fieldNames": ['id', 'x', "y"]31 },32 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]33 },34 "plotSoldPrice": {35 "reportName": "Гистограмма цены проданых товаров",36 "axis": {37 "xAxis": "Логарифм по основанию 10 от цены выставленного товара",38 "yAxis": "Количество проданных товаров из данного ценового интервала"39 },40 "return": {41 "type": "plot",42 "fieldLabel": {43 "id": "id",44 "x": "Логарифм по основанию 10 от цены выставленного товара",45 "y": "Количество проданных товаров из данного ценового интервала"46 },47 "fieldNames": ['id', 'x', "y"]48 },49 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]50 },51 "plotProbPrice": {52 "reportName": "График вероятности продажи товара из заданной ценовой категории",53 "axis": {54 "xAxis": "Логарифм по основанию 10 от цены выставленного товара",55 "yAxis": "Оценка вероятности продажи товара из данной ценовой категории"56 },57 "return": {58 "type": "plot",59 "fieldLabel": {60 "id": "id",61 "x": "Логарифм по основанию 10 от цены выставленного товара",62 "y": "Оценка вероятности продажи товара из данной ценовой категории"63 },64 "fieldNames": ['id', 'x', "y"]65 },66 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]67 },68 "plotProfPrice": {69 "reportName": "График прибыли от одного выставления товара из заданой ценовой категории",70 "axis": {71 "xAxis": "Логарифм по основанию 10 от цены выставленного товара",72 "yAxis": "Оценка прибыли от одного выставления товара из заданой ценовой категории"73 },74 "return": {75 "type": "plot",76 "fieldLabel": {77 "id": "id",78 "x": "Логарифм по основанию 10 от цены выставленного товара",79 "y": " Оценка прибыли от одного выставления товара из заданой ценовой категории"80 },81 "fieldNames": ['id', 'x', "y"]82 },83 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]84 },85 "plotPublishDay": {86 "reportName": "Гистограмма количества выставлений по дням недели",87 "axis": {88 "xAxis": "День недели",89 "yAxis": "Количество товаров которые были выставленый в данный день недели"90 },91 "return": {92 "type": "plot",93 "fieldLabel": {94 "id": "id",95 "x": "День недели",96 "y": "Количество товаров которые были выставленый в данный день недели"97 },98 "fieldNames": ['id', 'x', "y"]99 },100 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]101 },102 "plotSoldDay": {103 "reportName": "Гистограмма количества породаж в зависимости от дня выставления",104 "axis": {105 "xAxis": "День недели",106 "yAxis": "Количество проданых товаров которые были выставлены в данный день недели"107 },108 "return": {109 "type": "plot",110 "fieldLabel": {111 "id": "id",112 "x": "День недели",113 "y": "Количество проданых товаров которые были выставлены в данный день недели"114 },115 "fieldNames": ['id', 'x', "y"]116 },117 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]118 },119 "plotProbDay": {120 "reportName": "График вероятности продажи товара выставленного в заданый день недели",121 "axis": {122 "xAxis": "День недели",123 "yAxis": "Количество проданых товаров которые были выставлены в данный день недели"124 },125 "return": {126 "type": "plot",127 "fieldLabel": {128 "id": "id",129 "x": "День недели",130 "y": "Оценка вероятности продажи товара выставленного в заданный день недели"131 },132 "fieldNames": ['id', 'x', "y"]133 },134 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]135 },136 "plotCreatedDay": {137 "reportName": "Гистограмма количества продаж в каждый день недели ",138 "axis": {139 "xAxis": "День недели",140 "yAxis": "Количество товаров проданых в данный день"141 },142 "return": {143 "type": "plot",144 "fieldLabel": {145 "id": "id",146 "x": "День недели",147 "y": "Количество товаров проданых в данный день"148 },149 "fieldNames": ['id', 'x', "y"]150 },151 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]152 },153 "plotPublishTime": {154 "reportName": "Гистограмма количества выставлений в каждый часв течении дня",155 "axis": {156 "xAxis": "Время суток(час)",157 "yAxis": "Количество выставленых в заданый чвс товаров"158 },159 "return": {160 "type": "plot",161 "fieldLabel": {162 "id": "id",163 "x": "Время суток(час)",164 "y": "Количество выставленых в заданый чвс товаров"165 },166 "fieldNames": ['id', 'x', "y"]167 },168 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]169 },170 "plotSoldTime": {171 "reportName": "Гистограмма количества проданных товаров выставленых в заданое время",172 "axis": {173 "xAxis": "Время суток(час)",174 "yAxis": "Количество проданных товаров которые были выставлены в заданое время"175 },176 "return": {177 "type": "plot",178 "fieldLabel": {179 "id": "id",180 "x": "Время суток(час)",181 "y": "Количество проданных товаров которые были выставлены в заданое время"182 },183 "fieldNames": ['id', 'x', "y"]184 },185 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]186 },187 "plotProbTime": {188 "reportName": "График вероятности продажи товара выставленного в заданое время суток",189 "axis": {190 "xAxis": "Время суток(час)",191 "yAxis": "Оценка вероятности продажи товара выставленого заданое время суток"192 },193 "return": {194 "type": "plot",195 "fieldLabel": {196 "id": "id",197 "x": "Время суток(час)",198 "y": " Оценка вероятности продажи товара выставленого заданое время суток"199 },200 "fieldNames": ['id', 'x', "y"]201 },202 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]203 },204 "plotCreatedTime": {205 "reportName": "Гистограмма количетва продаж в каждый час дня",206 "axis": {207 "xAxis": "Время суток(час)",208 "yAxis": "Количество продынных товаров в заданое время суток"209 },210 "return": {211 "type": "plot",212 "fieldLabel": {213 "id": "id",214 "x": "Время суток(час)",215 "y": "Количество продынных товаров в заданое время суток"216 },217 "fieldNames": ['id', 'x', "y"]218 },219 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]220 },221 "plotCreatedTimeWithTZ": {222 "reportName": "Гистограмма количества продаж в каждый час дня с учетом часовых почсов",223 "axis": {224 "xAxis": "Время суток в штате где выло куплено товар",225 "yAxis": "Количество продынных товаров в заданое время суток с учетом часовых поясов"226 },227 "return": {228 "type": "plot",229 "fieldLabel": {230 "id": "id",231 "x": "Время суток в штате где выло куплено товар",232 "y": "Количество продынных товаров в заданое время суток с учетом часовых поясов"233 },234 "fieldNames": ['id', 'x', "y"]235 },236 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]237 },238 "tableCategoryPrice": {239 "reportName": "Таблица частот по ценовым категориям товаров",240 "return": {241 "type": "table",242 "fieldLabel": {243 "id": "id",244 "category_price": "Ценовая категория",245 "count_sold": "Количество проданных",246 "count_push": "Количество выставленых",247 "prob": "Оценка вероятности продажи",248 "prof_mounth": "Оценка прибыли за месяц",249 "new_prob": "Оценка вероятности продажи при выставлениия на 10 дней",250 "new_prof_mounth": "Оценка прибыли за месяц при выставлении на 10 дней",251 "delta_prof_mounth": "Разница в прибыли"252 },253 "fieldNames": [254 "id",255 "category_price",256 "count_sold",257 "count_push",258 "prob",259 "prof_mounth",260 "new_prob",261 "new_prof_mounth",262 "delta_prof_mounth"263 ]264 },265 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]266 },267 "tableCategoryID": {268 "reportName": "Таблица частот по категориям товаров",269 "return": {270 "type": "table",271 "fieldLabel": {272 "id": "id строки",273 "ebaycategory_id": "Номер категории",274 "count_sold": "Количество приданных",275 "count_push": "Количество выставленных",276 "mean_price": "Средняя цена по категории",277 "prob": "Оценка вероятности продажи",278 "prof_mounth": "Оценка прибыли за месяц",279 "new_prob": "Оценка вероятности продажи при выставлении на 10 дней",280 "new_prof_mounth": "Оценка прибыли за месяц при выставлении на 10 дней",281 "delta_prof_mounth": "Разница в прибыли"282 },283 "fieldNames": [284 "id",285 "ebaycategory_id",286 "count_sold",287 "count_push",288 "mean_price",289 "prob",290 "prof_mounth",291 "new_prob",292 "new_prof_mounth",293 "delta_prof_mounth"294 ]295 },296 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]297 },298 "tableProduct": {299 "reportName": "Таблица частот по отдельным товарам",300 "return": {301 "type": "table",302 "fieldLabel": {303 "id": "id строки",304 "ProductID": "ProductID",305 "count_sold": "Количество проданных",306 "count_push": "Количество выставленных",307 "price": "Цена товара",308 "prob": "Оценка вероятности продажи",309 "prof_mounth": "Оценка прибыли за месяц",310 "new_prob": "Оценка вероятности продажи при выставлении на 10 дней",311 "new_prof_mounth": "Оценка прибыли за месяц при выставлении на 10 дней",312 "delta_prof_mounth": "Разница прибыли"313 },314 "fieldNames": [315 "id",316 "ProductID",317 "count_sold",318 "count_push",319 "price",320 "prob",321 "prof_mounth",322 "new_prob",323 "new_prof_mounth",324 "delta_prof_mounth"325 ]326 },327 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]328 },329 "tableModel": {330 "reportName": "Таблица популярности каждой из марок мотоциклов",331 "paramsName": [],332 "return": {333 "type": "table",334 "fieldLabel": {335 "id": "id строки",336 "vehicle": "Марка мотоцикла",337 "vehicle_id": "id марки мотоцикла",338 "count_sold": "Количество проданных товаров которые подходят данной марке",339 "count_publish": "Количество выставленных товаров которые подходят данной марке"340 },341 "fieldNames": [342 "id",343 "vehicle",344 "vehicle_id",345 "count_sold",346 "count_publish"347 ]348 }349 },350 "tableProductModel": {351 "paramsName": [],352 "reportName": "Таблица популярности деталей по маркам которым она подходит",353 "return": {354 "type": "table",355 "fieldLabel": {356 "id": "id строки",357 "ProductID": "ProductID",358 "count_model_sold": "Количество проданых товаров которы подходят тем же маркам мотоциклов",359 "count_model_publish": "Количество выставленных товаров которые подходят тем же маркам мотоцыклов",360 "prob": "Оценка вероятности продажи товара который подходит тем же маркам мотоциклов"361 },362 "fieldNames": [363 "id",364 "ProductID",365 "count_model_sold",366 "count_model_publish",367 "prob"368 ]369 }370 },371 "bestProducts": {372 "paramsName": [],373 "reportName": "Список товаров которые продались больше всего на ebay",374 "return": {375 "type": "table",376 "fieldLabel": {377 "id": "id строки",378 "title": "Тайтл товара",379 "count_sold": "Количество продаж данного товара начиная с 2016-01-22",380 },381 "fieldNames": [382 "id",383 "title",384 "count_sold",385 ]386 }387 },388 "bestCompetitor": {389 "paramsName": [],390 "reportName": "Список продавцов и количество продаж этих продавцов",391 "return": {392 "type": "table",393 "fieldLabel": {394 "id": "id строки",395 "seller_name": "Ник продавца",396 "count_sold": "Количество продаж данного товара начиная с 2016-01-22",397 },398 "fieldNames": [399 "id",400 "seller_name",401 "count_sold",402 ]403 }404 },405 "NN": {406 "reportName": "Гистограмма цен выставленных товаров с задаными словами",407 "axis": {408 "xAxis": "Логарифм по основанию 10 от цены товара",409 "yAxis": "Количество продаж"410 },411 "return": {412 "type": "plot",413 "fieldLabel": {414 "id": "id",415 "x": "Логарифм по основанию 10 от цены товара",416 "y": "Количество продаж"417 },418 "fieldNames": ['id', 'x', "y"]419 },420 "paramsName": ["liketitle", "begstart_time", "endstart_time"]421 },422 "NNSold": {423 "reportName": "Гистограмма цен проданых товаров с задаными словами",424 "axis": {425 "xAxis": "логарифм по основанию 10 от цены товара",426 "yAxis": "Количество продаж"427 },428 "return": {429 "type": "plot",430 "fieldLabel": {431 "id": "id",432 "x": "Логарифм по основанию 10 от цены товара",433 "y": "Количество продаж"434 },435 "fieldNames": ['id', 'x', "y"]436 },437 "paramsName": ["liketitle", "begstart_time", "endstart_time"]438 },439 "soldProducts": {440 "reportName": "Таблица количества продаж каждого из товаров",441 "return": {442 "type": "table",443 "fieldLabel": {444 "id": "id",445 "ProductID": "ProductID",446 "count_sold": "Количество продаж"447 },448 "fieldNames": ['id', 'ProductID', "count_sold"]449 },450 "paramsName": ["brand", "likeebaycategory_id", "begadd_date", "endadd_date"]451 },452 "soldView": {453 "reportName": "Таблица соотношений покупок и просмотров лотов",454 "return": {455 "type": "table",456 "fieldLabel": {457 "id": "id",458 "ItemID": "ItemID",459 "count_sold": "Количество продаж",460 "count_view": "Количество просмотров лота",461 "prob": "Вероятность продажи товара на который зашли"462 },463 "fieldNames": ['id','ItemID', 'count_sold', "count_view", 'prob']464 },465 "paramsName": ["begadd_date", "endadd_date"]466 },467 "tablePublishTime": {468 "reportName": "Таблица количества выставлений на каждый час недели",469 "return": {470 "type": "table",471 "fieldLabel": {472 "id": "id",473 "Monday": "Monday",474 "Tuesday": "Tuesday",475 "Wednesday": "Wednesday",476 "Thursday": "Thursday",477 "Friday": "Friday",478 "Saturday": "Saturday",479 "Sunday": "Sunday"480 },481 "fieldNames": ['id',"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]482 },483 "paramsName": []484 }485 },486 "names": [487 "plotPublishPrice",488 "plotSoldPrice",489 "plotProbPrice",490 "plotProfPrice",491 "plotPublishDay",492 "plotSoldDay",493 "plotProbDay",494 "plotCreatedDay",495 "plotPublishTime",496 "plotSoldTime",497 "plotProbTime",498 "plotCreatedTime",499 "plotCreatedTimeWithTZ",500 "tableCategoryPrice",501 "tableCategoryID",502 "tableProduct",503 "tableModel",504 "tableProductModel",505 "bestProducts",506 "bestCompetitor",507 "NN",508 "NNSold",509 "tablePublishTime",510 "soldProducts",511 "soldView"512 ]513 };...

Full Screen

Full Screen

fetchDate.test.js

Source:fetchDate.test.js Github

copy

Full Screen

1'use strict'2import { expect } from 'chai'3import deepFreeze from 'deep-freeze'4import { fetchName, fetchRegistration, fetchClass } from '../fetchDate'5describe('fetchName test:', () => {6 it('Should return be a function', () => { 7 expect(fetchName).to.be.a('function') 8 }) 9 10 it('Any on params undefined should return "não encontrado"', () => {11 const paramsName = 'André Luís Brito Pimentel de Lira Ferraz Gomes'12 const paramsDateFirebase = undefined13 const after = "nao encontrado"14 expect(fetchName(paramsName, paramsDateFirebase)).equal(after)15 })16 17 it('Any on params undefined should return "não encontrado"', () => {18 const paramsName = undefined19 const paramsDateFirebase = deepFreeze([{'curso': "",'email': "",'matricula': "2011201001",'nome': "André Luís Brito Pimentel de Lira Ferraz Gomes"}]) 20 const after = "nao encontrado"21 expect(fetchName(paramsName, paramsDateFirebase)).equal(after)22 })23 24 it('Should return 2020101161', () => {25 const paramsName = 'Gustavo Costa de Albuquerque Maranhao Neto'26 const paramsDateFirebase = deepFreeze([{27 'anoLetivo': {28 '2021': {29 '1': {30 'MED02-14': {31 'AC1': 0,32 'AC1DP1': 0,33 'AC1DP2': 0,34 'AC1DP3': 0,35 'AC1SP1': 0,36 'AC1SP2': 0,37 'AC1SP3': 0,38 'ATT': 0,39 'MT1': 0,40 'MT2': 0,41 'MT3': 0,42 'codigo': "MED02-14",43 'mediaFinal': 0,44 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",45 'situacao': "Matriculado",46 'turma': "14FFP011", 47 },48 'MED02-15': {49 'AC1': 0,50 'AC1DP1': 0,51 'AC1DP2': 0,52 'AC1DP3': 0,53 'AC1SP1': 0,54 'AC1SP2': 0,55 'AC1SP3': 0,56 'ATT': 0,57 'MT1': 0,58 'MT2': 0,59 'MT3': 0,60 'codigo': "MED02-15",61 'mediaFinal': 0,62 'nome': "Estudo da função dos órgãos e sistemas II",63 'situacao': "Matriculado",64 'turma': "15EFOS061", 65 }, 66 67 }68 }69 },70 'curso': "",71 'email': "",72 'matricula': "2020101161",73 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"74 }]) 75 const after = "Gustavo Costa de Albuquerque Maranhão Neto"76 expect(fetchName(paramsName, paramsDateFirebase)).equal(after) 77 })78 79 it('Should return 2020101161', () => {80 const paramsName = 'Filipe Luiz Rodrigues Correia'81 const paramsDateFirebase = deepFreeze([{82 'anoLetivo': {83 '2021': {84 '1': {85 'MED02-14': {86 'AC1': 0,87 'AC1DP1': 0,88 'AC1DP2': 0,89 'AC1DP3': 0,90 'AC1SP1': 0,91 'AC1SP2': 0,92 'AC1SP3': 0,93 'ATT': 0,94 'MT1': 0,95 'MT2': 0,96 'MT3': 0,97 'codigo': "MED02-14",98 'mediaFinal': 0,99 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",100 'situacao': "Matriculado",101 'turma': "14FFP011", 102 },103 'MED02-15': {104 'AC1': 0,105 'AC1DP1': 0,106 'AC1DP2': 0,107 'AC1DP3': 0,108 'AC1SP1': 0,109 'AC1SP2': 0,110 'AC1SP3': 0,111 'ATT': 0,112 'MT1': 0,113 'MT2': 0,114 'MT3': 0,115 'codigo': "MED02-15",116 'mediaFinal': 0,117 'nome': "Estudo da função dos órgãos e sistemas II",118 'situacao': "Matriculado",119 'turma': "15EFOS061", 120 }, 121 122 }123 }124 },125 'curso': "",126 'email': "",127 'matricula': "2020101161",128 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"129 }]) 130 const after = "nao encontrado"131 expect(fetchName(paramsName, paramsDateFirebase)).equal(after) 132 }) 133})134describe('fetchRegistration test:', () => {135 it('Should return be a function', () => {136 expect(fetchRegistration).to.be.a('function')137 })138 139 it('All params undefineds should return "não encontrado"', () => {140 expect(fetchRegistration()).equal("nao encontrado")141 })142 143 it('Any on params undefined should return "não encontrado"', () => {144 const paramsName = 'André Luís Brito Pimentel de Lira Ferraz Gomes'145 const paramsDateFirebase = undefined146 const after = "nao encontrado"147 expect(fetchRegistration(paramsName, paramsDateFirebase)).equal(after)148 })149 150 it('Any on params undefined should return "não encontrado"', () => {151 const paramsName = undefined152 const paramsDateFirebase = deepFreeze([{'curso': "",'email': "",'matricula': "2011201001",'nome': "André Luís Brito Pimentel de Lira Ferraz Gomes"}]) 153 const after = "nao encontrado"154 expect(fetchRegistration(paramsName, paramsDateFirebase)).equal(after)155 })156 157 it('Should return 2020101161', () => {158 const paramsName = 'Gustavo Costa de Albuquerque Maranhao Neto'159 const paramsDateFirebase = deepFreeze([{160 'anoLetivo': {161 '2021': {162 '1': {163 'MED02-14': {164 'AC1': 0,165 'AC1DP1': 0,166 'AC1DP2': 0,167 'AC1DP3': 0,168 'AC1SP1': 0,169 'AC1SP2': 0,170 'AC1SP3': 0,171 'ATT': 0,172 'MT1': 0,173 'MT2': 0,174 'MT3': 0,175 'codigo': "MED02-14",176 'mediaFinal': 0,177 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",178 'situacao': "Matriculado",179 'turma': "14FFP011", 180 },181 'MED02-15': {182 'AC1': 0,183 'AC1DP1': 0,184 'AC1DP2': 0,185 'AC1DP3': 0,186 'AC1SP1': 0,187 'AC1SP2': 0,188 'AC1SP3': 0,189 'ATT': 0,190 'MT1': 0,191 'MT2': 0,192 'MT3': 0,193 'codigo': "MED02-15",194 'mediaFinal': 0,195 'nome': "Estudo da função dos órgãos e sistemas II",196 'situacao': "Matriculado",197 'turma': "15EFOS061", 198 }, 199 200 }201 }202 },203 'curso': "",204 'email': "",205 'matricula': "2020101161",206 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"207 }]) 208 const after = "2020101161"209 expect(fetchRegistration(paramsName, paramsDateFirebase)).equal(after) 210 })211 212 it('Should return nao encontrado', () => {213 const paramsName = 'Filipe Luiz Rodrigues Correia'214 const paramsDateFirebase = deepFreeze([{215 'anoLetivo': {216 '2021': {217 '1': {218 'MED02-14': {219 'AC1': 0,220 'AC1DP1': 0,221 'AC1DP2': 0,222 'AC1DP3': 0,223 'AC1SP1': 0,224 'AC1SP2': 0,225 'AC1SP3': 0,226 'ATT': 0,227 'MT1': 0,228 'MT2': 0,229 'MT3': 0,230 'codigo': "MED02-14",231 'mediaFinal': 0,232 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",233 'situacao': "Matriculado",234 'turma': "14FFP011", 235 },236 'MED02-15': {237 'AC1': 0,238 'AC1DP1': 0,239 'AC1DP2': 0,240 'AC1DP3': 0,241 'AC1SP1': 0,242 'AC1SP2': 0,243 'AC1SP3': 0,244 'ATT': 0,245 'MT1': 0,246 'MT2': 0,247 'MT3': 0,248 'codigo': "MED02-15",249 'mediaFinal': 0,250 'nome': "Estudo da função dos órgãos e sistemas II",251 'situacao': "Matriculado",252 'turma': "15EFOS061", 253 }, 254 255 }256 }257 },258 'curso': "",259 'email': "",260 'matricula': "2020101161",261 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"262 }]) 263 const after = "nao encontrado"264 expect(fetchRegistration(paramsName, paramsDateFirebase)).equal(after) 265 }) 266})267describe('fetchClass test:', () => {268 it('Should return a be function', () => {269 expect(fetchClass).to.be.a('function')270 })271 272 it('All params undefineds should return "não encontrado"', () => {273 expect(fetchClass()).equal("nao econtrado")274 })275 276 it('Any on params undefined should return "não encontrado"', () => {277 const paramsName = 'André Luís Brito Pimentel de Lira Ferraz Gomes'278 const paramsDateFirebase = deepFreeze([{'curso': "",'email': "",'matricula': "2011201001",'nome': "André Luís Brito Pimentel de Lira Ferraz Gomes"}]) 279 const paramsDiscipline = undefined280 const after = "nao econtrado"281 expect(fetchClass(paramsName, paramsDateFirebase, paramsDiscipline)).equal(after)282 })283 284 it('Any on params undefined should return "não encontrado"', () => {285 const paramsName = 'André Luís Brito Pimentel de Lira Ferraz Gomes'286 const paramsDateFirebase = undefined287 const paramsDiscipline = 'MED02-14'288 const after = "nao econtrado"289 expect(fetchClass(paramsName, paramsDateFirebase, paramsDiscipline)).equal(after)290 })291 292 it('Any on params undefined should return "não encontrado"', () => {293 const paramsName = undefined294 const paramsDateFirebase = deepFreeze([{'curso': "",'email': "",'matricula': "2011201001",'nome': "André Luís Brito Pimentel de Lira Ferraz Gomes"}]) 295 const paramsDiscipline = 'MED02-14'296 const after = "nao econtrado"297 expect(fetchClass(paramsName, paramsDateFirebase, paramsDiscipline)).equal(after)298 })299 300 it('All on params not should return "não encontrado"', () => {301 const paramsName = 'Gustavo Costa de Albuquerque Maranhao Neto'302 const paramsDateFirebase = deepFreeze([{303 'anoLetivo': {304 '2021': {305 '1': {306 'MED02-14': {307 'AC1': 0,308 'AC1DP1': 0,309 'AC1DP2': 0,310 'AC1DP3': 0,311 'AC1SP1': 0,312 'AC1SP2': 0,313 'AC1SP3': 0,314 'ATT': 0,315 'MT1': 0,316 'MT2': 0,317 'MT3': 0,318 'codigo': "MED02-14",319 'mediaFinal': 0,320 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",321 'situacao': "Matriculado",322 'turma': "14FFP011", 323 },324 'MED02-15': {325 'AC1': 0,326 'AC1DP1': 0,327 'AC1DP2': 0,328 'AC1DP3': 0,329 'AC1SP1': 0,330 'AC1SP2': 0,331 'AC1SP3': 0,332 'ATT': 0,333 'MT1': 0,334 'MT2': 0,335 'MT3': 0,336 'codigo': "MED02-15",337 'mediaFinal': 0,338 'nome': "Estudo da função dos órgãos e sistemas II",339 'situacao': "Matriculado",340 'turma': "15EFOS061", 341 }, 342 343 }344 }345 },346 'curso': "",347 'email': "",348 'matricula': "2020101161",349 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"350 }]) 351 const paramsDiscipline = 'MED02-14'352 const after = "14FFP011"353 expect(fetchClass(paramsName, paramsDateFirebase, paramsDiscipline)).equal(after) 354 })355 356 it('All on params not should return "não encontrado"', () => {357 const paramsName = 'Gustavo Costa de Albuquerque Maranhao Neto'358 const paramsDateFirebase = deepFreeze([{359 'anoLetivo': {360 '2021': {361 '1': {362 'MED02-14': {363 'AC1': 0,364 'AC1DP1': 0,365 'AC1DP2': 0,366 'AC1DP3': 0,367 'AC1SP1': 0,368 'AC1SP2': 0,369 'AC1SP3': 0,370 'ATT': 0,371 'MT1': 0,372 'MT2': 0,373 'MT3': 0,374 'codigo': "MED02-14",375 'mediaFinal': 0,376 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",377 'situacao': "Matriculado",378 'turma': "14FFP011", 379 },380 'MED02-15': {381 'AC1': 0,382 'AC1DP1': 0,383 'AC1DP2': 0,384 'AC1DP3': 0,385 'AC1SP1': 0,386 'AC1SP2': 0,387 'AC1SP3': 0,388 'ATT': 0,389 'MT1': 0,390 'MT2': 0,391 'MT3': 0,392 'codigo': "MED02-15",393 'mediaFinal': 0,394 'nome': "Estudo da função dos órgãos e sistemas II",395 'situacao': "Matriculado",396 'turma': "15EFOS061", 397 }, 398 399 }400 }401 },402 'curso': "",403 'email': "",404 'matricula': "2020101161",405 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"406 }]) 407 const paramsDiscipline = 'MED02-16'408 const after = "nao encontrado"409 expect(fetchClass(paramsName, paramsDateFirebase, paramsDiscipline)).equal(after)410 })411 412 it('All on params not should return "não encontrado"', () => {413 const paramsName = 'Filipe Luiz Rodrigues Correia'414 const paramsDateFirebase = deepFreeze([{415 'anoLetivo': {416 '2021': {417 '1': {418 'MED02-14': {419 'AC1': 0,420 'AC1DP1': 0,421 'AC1DP2': 0,422 'AC1DP3': 0,423 'AC1SP1': 0,424 'AC1SP2': 0,425 'AC1SP3': 0,426 'ATT': 0,427 'MT1': 0,428 'MT2': 0,429 'MT3': 0,430 'codigo': "MED02-14",431 'mediaFinal': 0,432 'nome': "Farmacocinética e farmacodinâmica dos principais grupos de medicamentos",433 'situacao': "Matriculado",434 'turma': "14FFP011", 435 },436 'MED02-15': {437 'AC1': 0,438 'AC1DP1': 0,439 'AC1DP2': 0,440 'AC1DP3': 0,441 'AC1SP1': 0,442 'AC1SP2': 0,443 'AC1SP3': 0,444 'ATT': 0,445 'MT1': 0,446 'MT2': 0,447 'MT3': 0,448 'codigo': "MED02-15",449 'mediaFinal': 0,450 'nome': "Estudo da função dos órgãos e sistemas II",451 'situacao': "Matriculado",452 'turma': "15EFOS061", 453 }, 454 455 }456 }457 },458 'curso': "",459 'email': "",460 'matricula': "2020101161",461 'nome': "Gustavo Costa de Albuquerque Maranhão Neto"462 }]) 463 const paramsDiscipline = 'MED02-16'464 const after = "nao encontrado"465 expect(fetchClass(paramsName, paramsDateFirebase, paramsDiscipline)).equal(after)466 }) ...

Full Screen

Full Screen

ParamsBuilder.js

Source:ParamsBuilder.js Github

copy

Full Screen

1import moment from 'moment';2import { toInteger, toNumber, isBoolean, isArray } from 'lodash';3import FORMATS from '../constants/formats';4import { isID } from './commonUtils';5const formatDate = FORMATS.date;6const formatOnlyTime = FORMATS.time;7const formatTime = FORMATS.fullDateTime;8export default class ParamsBuilder {9 RULES = {10 noCondition: 'noCondition',11 isExist: 'isExist',12 isID: 'isID',13 isBoolean: 'isBoolean',14 isNumber: 'isNumber',15 isDate: 'isDate',16 isDateTime: 'isDateTime',17 isString: 'isString',18 isDateRange: 'isDateRange',19 isDateTimeRange: 'isDateTimeRange',20 isISOStringRange: 'isISOStringRange',21 isArrayID: 'isArrayID',22 isArrayString: 'isArrayString',23 isNumberRange: 'isNumberRange',24 isTimeRange: 'isTimeRange',25 isPositiveNumber: 'isPositiveNumber',26 isTrue: 'isTrue',27 };28 fields = [];29 values = [];30 addValue(paramsName, value) {31 this.values.push({32 paramsName,33 value,34 });35 }36 addField(rule, objectName, paramsName = null) {37 this.fields.push({38 rule,39 objectName,40 paramsName: paramsName || objectName,41 });42 }43 addRangeField(rule, valueRange, paramsNames = []) {44 this.fields.push({45 rule,46 valueRange,47 paramsNames,48 });49 }50 biuldParams(initObject) {51 const params = {};52 this.values.forEach(item => {53 params[item.paramsName] = item.value;54 });55 this.fields.forEach(field => {56 const { rule, objectName, paramsName } = field;57 const value = initObject[objectName];58 switch (rule) {59 case this.RULES.isExist: {60 if (value !== undefined && value !== null) {61 params[paramsName] = value;62 }63 break;64 }65 case this.RULES.isID: {66 if (isID(value)) {67 params[paramsName] = toInteger(value);68 }69 break;70 }71 case this.RULES.isBoolean: {72 if (isBoolean(value)) {73 params[paramsName] = Boolean(value);74 }75 break;76 }77 case this.RULES.isNumber: {78 // eslint-disable-next-line no-restricted-globals79 if (!isNaN(toNumber(value))) {80 params[paramsName] = toNumber(value);81 }82 break;83 }84 case this.RULES.isString: {85 if (value !== undefined && value !== null && value !== '') {86 params[paramsName] = value;87 }88 break;89 }90 case this.RULES.isDate: {91 const valueDate = moment(value);92 if (valueDate) {93 params[paramsName] = valueDate.format(formatDate);94 }95 break;96 }97 case this.RULES.isDateTime: {98 const valueDateTime = moment(value);99 if (valueDateTime) {100 params[paramsName] = valueDateTime.format(formatTime);101 }102 break;103 }104 case this.RULES.isDateRange: {105 this.checkDateRange(params, field);106 break;107 }108 case this.RULES.isDateTimeRange: {109 this.checkDateTimeRange(params, field);110 break;111 }112 case this.RULES.isISOStringRange: {113 this.checkISOStringRange(params, field);114 break;115 }116 case this.RULES.isTimeRange: {117 this.checkTimeRange(params, field);118 break;119 }120 case this.RULES.isArrayID: {121 const arrayID = this.getArrayID(value);122 if (arrayID.length > 0) {123 params[paramsName] = arrayID;124 }125 break;126 }127 case this.RULES.isArrayString: {128 const arrayString = this.getArrayString(value);129 if (arrayString.length > 0) {130 params[paramsName] = arrayString;131 }132 break;133 }134 case this.RULES.isNumberRange: {135 this.checkNumberRange(params, field);136 break;137 }138 case this.RULES.isPositiveNumber: {139 const numValue = toNumber(value);140 // eslint-disable-next-line no-restricted-globals141 if (!isNaN(numValue) && numValue > 0) {142 params[paramsName] = numValue;143 }144 break;145 }146 case this.RULES.isTrue: {147 if (isBoolean(value) && value) {148 params[paramsName] = Boolean(value);149 }150 break;151 }152 default: {153 params[paramsName] = value;154 }155 }156 });157 return params;158 }159 checkDateRange(params, field) {160 const { valueRange, paramsNames } = field;161 if (!valueRange) {162 return;163 }164 valueRange.forEach((value, index) => {165 const paramsName = paramsNames[index];166 if (!value || !paramsName) {167 return;168 }169 if(moment.isMoment(value)) {170 params[paramsName] = value.format(formatDate);171 } else {172 const valueDate = moment(value);173 if (valueDate) {174 params[paramsName] = valueDate.format(formatDate);175 }176 }177 });178 }179 checkDateTimeRange(params, field) {180 const { valueRange, paramsNames } = field;181 if (!valueRange) {182 return;183 }184 valueRange.forEach((value, index) => {185 const paramsName = paramsNames[index];186 if (!value || !paramsName) {187 return;188 }189 if(moment.isMoment(value)) {190 params[paramsName] = value.format(formatTime);191 } else {192 const valueDate = moment(value);193 if (valueDate) {194 params[paramsName] = valueDate.format(formatTime);195 }196 }197 });198 }199 checkISOStringRange(params, field) {200 const { valueRange, paramsNames } = field;201 if (!valueRange) {202 return;203 }204 valueRange.forEach((value, index) => {205 const paramsName = paramsNames[index];206 if (!value || !paramsName) {207 return;208 }209 if(moment.isMoment(value)) {210 params[paramsName] = value.toISOString();211 } else {212 const valueDate = moment(value);213 if (valueDate) {214 params[paramsName] = valueDate.toISOString();215 }216 }217 });218 }219 checkTimeRange(params, field) {220 const { valueRange, paramsNames } = field;221 if (!valueRange) {222 return;223 }224 valueRange.forEach((value, index) => {225 const paramsName = paramsNames[index];226 if (!value || !paramsName) {227 return;228 }229 const valueDate = moment(value);230 if (valueDate) {231 params[paramsName] = valueDate.format(formatOnlyTime);232 }233 });234 }235 checkNumberRange(params, field) {236 const { valueRange, paramsNames } = field;237 if (!valueRange) {238 return;239 }240 valueRange.forEach((value, index) => {241 const paramsName = paramsNames[index];242 if (!value || !paramsName) {243 return;244 }245 const valueNumber = toNumber(value);246 if (valueNumber) {247 params[paramsName] = valueNumber;248 }249 });250 }251 getArrayID(rawArrayID) {252 if (!isArray(rawArrayID)) {253 return [];254 }255 const arrayID = rawArrayID.filter(item => {256 return isID(item);257 });258 return arrayID;259 }260 getArrayString(rawArrayString) {261 if (!isArray(rawArrayString)) {262 return [];263 }264 const arrayString = rawArrayString.filter(item => {265 return Boolean(item);266 });267 return arrayString;268 }...

Full Screen

Full Screen

middlewareCreators.js

Source:middlewareCreators.js Github

copy

Full Screen

1import { applySession } from 'next-session';2import querystring from 'querystring';3import Shopify from 'shopify-api-node';4import createEnableCookies from './createEnableCookies';5import createOAuthCallback from './createOAuthCallback';6import createOAuthStart from './createOAuthStart';7import createRequestStorageAccess from './createRequestStorageAccess';8import createTopLevelOAuthRedirect from './createTopLevelOAuthRedirect';9import { redirectToAuth } from './helpers';10import {11 createTestCookie,12 destroyTopLevelOAuthCookie,13 grantedStorageAccess,14 hasCookieAccess,15 shouldPerformInlineOAuth16} from './helpers';17import shopifyResourceTypes from './shopifyResourceTypes';18// to be used in pages and apis19export const createSetSessionMiddleware = ({ prepareSessionOptions }) => async (req, res, next) => {20 const options = await prepareSessionOptions();21 await applySession(req, res, options);22 await next();23};24export const createEnableCookiesMiddleware = ({ apiKey, paramsName }) => async (req, res, next) => {25 const params = req.query[paramsName];26 if (params.length === 2 && params[0] === 'auth' && params[1] === 'enable_cookies') {27 const enableCookies = createEnableCookies(apiKey);28 await enableCookies(req, res);29 return;30 }31 await next();32};33export const createGetAuthUrlMiddleware = ({34 sharedSecret,35 apiKey,36 scopes,37 accessTokenTimeout,38 accessMode,39 paramsName40}) => async (req, res, next) => {41 const params = req.query[paramsName];42 if (params.length === 1 && params[0] === 'auth') {43 if (!hasCookieAccess(req) && !grantedStorageAccess(req)) {44 const requestStorageAccess = createRequestStorageAccess(apiKey);45 await requestStorageAccess(req, res);46 return;47 }48 if (shouldPerformInlineOAuth(req, res)) {49 const oAuthStart = createOAuthStart({50 paramsName,51 sharedSecret,52 apiKey,53 scopes,54 accessTokenTimeout,55 accessMode56 });57 await oAuthStart(req, res);58 return;59 } else {60 const topLevelOAuthRedirect = createTopLevelOAuthRedirect(apiKey, '/api/auth/inline');61 await topLevelOAuthRedirect(req, res);62 return;63 }64 }65 await next();66};67export const createHandleInlineAuthMiddleware = ({68 sharedSecret,69 apiKey,70 scopes,71 accessTokenTimeout,72 accessMode,73 paramsName74}) => async (req, res, next) => {75 const params = req.query[paramsName];76 if (params.length === 2 && params[0] === 'auth' && params[1] === 'inline') {77 const oAuthStart = createOAuthStart({78 paramsName,79 sharedSecret,80 apiKey,81 scopes,82 accessTokenTimeout,83 accessMode84 });85 await oAuthStart(req, res);86 return;87 }88 await next();89};90export const createGetAccessTokenMiddleware = ({91 sharedSecret,92 apiKey,93 scopes,94 accessTokenTimeout,95 accessMode,96 paramsName,97 apiVersion,98 autoLimit,99 presentmentPrices,100 shopifyAPITimeout,101 whatToDoAfterAuth102}) => async (req, res, next) => {103 const params = req.query[paramsName];104 if (params.length === 2 && params[0] === 'auth' && params[1] === 'callback') {105 const oAuthCallback = createOAuthCallback({106 paramsName,107 sharedSecret,108 apiKey,109 scopes,110 accessTokenTimeout,111 accessMode,112 apiVersion,113 autoLimit,114 presentmentPrices,115 shopifyAPITimeout,116 whatToDoAfterAuth117 });118 await oAuthCallback(req, res);119 return;120 }121 await next();122};123export const createHandleShopifyAPIMiddleware = ({124 paramsName,125 apiVersion,126 autoLimit,127 presentmentPrices,128 shopifyAPITimeout129}) => async (req, res, next) => {130 const params = req.query[paramsName];131 const [resourceName, methodName] = params;132 if (133 params.length === 2 &&134 shopifyResourceTypes[resourceName] !== undefined &&135 shopifyResourceTypes[resourceName][methodName] !== undefined136 ) {137 const { session } = req;138 if (session && session.accessToken) {139 destroyTopLevelOAuthCookie(req, res);140 const { shopName, accessToken } = session;141 const shopify = new Shopify({142 shopName,143 accessToken,144 apiVersion,145 autoLimit,146 presentmentPrices,147 timeout: shopifyAPITimeout148 });149 const queryData = req.query;150 const bodyData = req.body ?? {};151 const allData = { ...queryData, ...bodyData };152 const parameters = shopifyResourceTypes[resourceName][methodName].map(153 (parameterName) => allData[parameterName]154 );155 try {156 const result = await shopify[resourceName][methodName](...parameters);157 res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(result));158 return;159 } catch (err) {160 redirectToAuth(req, res);161 return;162 }163 }164 createTestCookie(req, res);165 redirectToAuth(req, res);166 return;167 }168 await next();169};170// to be used in pages and apis171export const createLoginAgainIfDifferentShopMiddleware = () => async (req, res, next) => {172 const { query: tmpQuery, session, url } = req;173 const query = tmpQuery ?? querystring.parse(url.split('?')[1] ?? '');174 if (session && query && query.shop && session.shop && session.shop != query.shop) {175 console.log('loginAgainIfDifferentShopMiddleware', req.url);176 req.session.destroy();177 redirectToAuth(req, res);178 }179 await next();180};181// to be used in pages and apis182export const createVerifyTokenMiddleware = ({ paramsName }) => async (req, res, next) => {183 const params = req.query && req.query[paramsName];184 const [resourceName, methodName] = params ?? [];185 if (186 !params ||187 params.length !== 2 ||188 (resourceName && shopifyResourceTypes[resourceName] === undefined) ||189 (resourceName &&190 methodName &&191 shopifyResourceTypes[resourceName] &&192 shopifyResourceTypes[resourceName][methodName] === undefined)193 ) {194 const { session } = req;195 if (session && session.accessToken) {196 destroyTopLevelOAuthCookie(req, res);197 const { shopName, accessToken } = session;198 const shopify = new Shopify({199 shopName,200 accessToken201 });202 try {203 await shopify.metafield.list();204 } catch (err) {205 redirectToAuth(req, res);206 return;207 }208 await next();209 return;210 }211 createTestCookie(req, res);212 redirectToAuth(req, res);213 return;214 }215 await next();216};217export const createVerifyAPIRoutesMiddleware = ({ paramsName }) => async (req, res, next) => {218 const params = req.query[paramsName];219 const [resourceName, methodName] = params;220 if (221 (params.length === 1 && params[0] === 'auth') ||222 (params.length === 2 && params[0] === 'auth' && params[1] === 'callback') ||223 (params.length === 2 &&224 shopifyResourceTypes[resourceName] !== undefined &&225 shopifyResourceTypes[resourceName][methodName] !== undefined)226 ) {227 if (req.redirectPath) {228 await next();229 return;230 }231 } else {232 res.writeHead(400).end('Route API not found');233 return;234 }...

Full Screen

Full Screen

SideBar.js

Source:SideBar.js Github

copy

Full Screen

1import React from 'react';2import Drawer from '@material-ui/core/Drawer';3import Hidden from '@material-ui/core/Hidden';4import List from '@material-ui/core/List';5import ListItem from '@material-ui/core/ListItem';6import { makeStyles } from '@material-ui/core/styles';7import { withRouter } from 'react-router';8import compose from 'recompose/compose';9const useStyles = makeStyles((theme) => ({10 root: {11 display: 'flex',12 width: '12%'13 },14 drawer: {15 [theme.breakpoints.up('sm')]: {16 flexShrink: 017 }18 },19 toolbar: theme.mixins.toolbar,20 drawerPaper: {21 zIndex: 'inherit',22 paddingTop: '32px',23 width: '12%',24 minWidth: '160px'25 },26 activeButton: {27 background: '#9400D3',28 width: '5px',29 height: '40px'30 },31 navBarStyle: {32 display: 'flex',33 flexDirection: 'row'34 }35}));36function ResponsiveDrawer(props) {37 const toggleDrawer = () => (event) => {38 if (39 event.type === 'keydown' &&40 (event.key === 'Tab' || event.key === 'Shift')41 ) {42 return;43 }44 props.hideLeftDrawer();45 };46 const handleTabClick = (navItem) => {47 props.history.push(navItem.hrefLink);48 };49 const navBarItemList = [50 { title: 'Courses', hrefLink: '/courses', paramsName: '/' },51 {52 title: 'Teaching Material',53 hrefLink: '/teaching_materials',54 paramsName: '/teaching_materials'55 },56 {57 title: 'Class Notes',58 hrefLink: '/class_notes',59 paramsName: '/class_notes'60 },61 {62 title: 'Requisite Groups',63 hrefLink: '/requisite_groups',64 paramsName: '/requisite_groups'65 },66 { title: 'Cohorts', hrefLink: '/cohorts', paramsName: '/cohorts' },67 { title: 'Raw Topics', hrefLink: '/raw_topics', paramsName: '/raw_topics' },68 { title: 'Videos', hrefLink: '/videos', paramsName: '/videos' },69 { title: 'TMBs', hrefLink: '/tmbs', paramsName: '/tmbs' }70 ];71 const classes = useStyles();72 let { location } = props;73 const drawer = (74 <List>75 {navBarItemList.map((item, index) => (76 <div key={index} className={classes.navBarStyle}>77 <ListItem button onClick={handleTabClick.bind(this, item)}>78 {item.title}79 </ListItem>80 {location.pathname === item.paramsName && (81 <div className={classes.activeButton} />82 )}83 </div>84 ))}85 </List>86 );87 return (88 <div className={classes.root}>89 <Hidden smUp implementation="css">90 <Drawer91 variant="temporary"92 open={props.isMobileView}93 classes={{94 paper: classes.drawerPaper95 }}96 ModalProps={{97 keepMounted: true // Better open performance on mobile.98 }}99 onClose={toggleDrawer()} // Close perfomance on mobile100 >101 {drawer}102 </Drawer>103 </Hidden>104 <Hidden xsDown implementation="css">105 <Drawer106 className={classes.drawer}107 variant="permanent"108 classes={{109 paper: classes.drawerPaper110 }}111 >112 <div className={classes.toolbar} />113 {drawer}114 </Drawer>115 </Hidden>116 </div>117 );118}...

Full Screen

Full Screen

Route.js

Source:Route.js Github

copy

Full Screen

1import React, { useContext } from 'react'2import pathToRegexp from 'path-to-regexp'3import RouterContext from './RouterContext'4/**5 * Route渲染的三种方式6 * 1、component 渲染传入的组件7 * 2、render 渲染render函数的返回值8 * 3、children 也是渲染children函数的返回值,但是无论是否匹配都会渲染,前两者只有匹配才会渲染9 */10export default function Route(props) {11 const context = useContext(RouterContext)12 let { path = '/', component: Component, exact = false, render, children } = props13 path = typeof path === 'object' ? path.pathname : path14 const pathname = context.location.pathname15 let paramsName = []16 // exact 表示是否精准匹配17 // /user/detail/:id /user/detail/122324318 const reg = pathToRegexp(path, paramsName, { end: exact })19 paramsName = paramsName.map(item => item.name) // ['id']20 const routeProps = {21 history: context.history,22 location: context.location23 }24 25 const matched = pathname.match(reg)26 // 匹配成功才会有match这个属性27 if (matched) {28 const [url, ...values] = matched // values: ['1223243']29 const params = paramsName.reduce((memo, cur, index) => {30 memo[cur] = values[index]31 return memo32 }, {})33 // 构造路由组件的三个属性34 const match = {35 path,36 url,37 params,38 isExact: path === url39 }40 routeProps.match = match41 if (Component) {42 return <Component {...routeProps} />43 } else if (render) {44 return render(routeProps)45 } else if (children) {46 return children(routeProps)47 } else {48 return null49 }50 }51 if (children) {52 return children(routeProps)53 } else {54 return null55 }56}57// export default class Route extends React.Component {58// static contextType = RouterContext59// render() {60// const { path = '/', component: Component, exact = false } = this.props61// const pathname = this.context.location.pathname62// let paramsName = []63// // exact 表示是否精准匹配64// // /user/detail/:id /user/detail/122324365// const reg = pathToRegexp(path, paramsName, { end: exact })66// paramsName = paramsName.map(item => item.name) // ['id']67// const matched = pathname.match(reg)68// if (matched) {69// const [url, ...values] = matched // values: ['1223243']70// const params = paramsName.reduce((memo, cur, index) => {71// memo[cur] = values[index]72// return memo73// }, {})74// // 构造路由组件的三个属性75// const routeProps = {76// history: this.context.history,77// location: this.context.location,78// match: {79// path,80// url,81// params,82// isExact: path === url83// }84// }85// return <Component {...routeProps} />86// }87// return null88// }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import {2 createEnableCookiesMiddleware,3 createGetAccessTokenMiddleware,4 createGetAuthUrlMiddleware,5 createHandleInlineAuthMiddleware,6 createHandleShopifyAPIMiddleware,7 createLoginAgainIfDifferentShopMiddleware,8 createSetSessionMiddleware,9 createVerifyAPIRoutesMiddleware,10 createVerifyTokenMiddleware11} from './middlewareCreators';12const functions = {};13const createNextShopifyFunctions = ({14 prepareSessionOptions,15 sharedSecret,16 apiKey,17 scopes,18 accessTokenTimeout = 60000,19 accessMode = '',20 paramsName = 'fns',21 apiVersion = '2020-10',22 autoLimit = false,23 presentmentPrices = false,24 shopifyAPITimeout = 60000,25 // eslint-disable-next-line no-unused-vars26 whatToDoAfterAuth = (req, res, shopify) => {27 res.redirect('/');28 }29}) => {30 if (Object.keys(functions).length > 0) {31 return functions;32 }33 functions.setSessionMiddleware = createSetSessionMiddleware({34 prepareSessionOptions35 });36 functions.enableCookiesMiddleware = createEnableCookiesMiddleware({37 apiKey,38 paramsName39 });40 functions.getAuthUrlMiddleware = createGetAuthUrlMiddleware({41 sharedSecret,42 apiKey,43 scopes,44 accessTokenTimeout,45 accessMode,46 paramsName47 });48 functions.handleInlineAuthMiddleware = createHandleInlineAuthMiddleware({49 sharedSecret,50 apiKey,51 scopes,52 accessTokenTimeout,53 accessMode,54 paramsName55 });56 functions.getAccessTokenMiddleware = createGetAccessTokenMiddleware({57 sharedSecret,58 apiKey,59 scopes,60 accessTokenTimeout,61 accessMode,62 paramsName,63 apiVersion,64 autoLimit,65 presentmentPrices,66 shopifyAPITimeout,67 whatToDoAfterAuth68 });69 functions.loginAgainIfDirrentShopMiddleware = createLoginAgainIfDifferentShopMiddleware();70 functions.verifyTokenMiddleware = createVerifyTokenMiddleware({ paramsName });71 functions.handleShopifyAPIMiddleware = createHandleShopifyAPIMiddleware({72 paramsName,73 apiVersion,74 autoLimit,75 presentmentPrices,76 shopifyAPITimeout77 });78 functions.verifyAPIRoutesMiddleware = createVerifyAPIRoutesMiddleware({79 paramsName80 });81 return functions;82};...

Full Screen

Full Screen

decorators.js

Source:decorators.js Github

copy

Full Screen

1import Ember from 'ember';2import Changeset from 'ember-changeset';3import { bsPromise, bsCheck } from '../models/utils';4const { observer, computed } = Ember;5export function queryParams(paramsName) {6 return (target, key, desc) => {7 paramsName = paramsName || key;8 return {9 ...desc,10 initializer() {11 return Ember.computed.alias(`_z_controller.${paramsName}`);12 }13 };14 };15}16export function showPage4Prop(pageName, prop) {17 return function(target, key, descriptor) {18 let func = descriptor.value;19 descriptor.value = Ember.on('didInsertElement', observer.call(null, prop, async function() {20 await bsPromise();21 let f7app = window.f7app;22 let propVal = this.get(prop);23 let shouldLoad = func.call(this, propVal);24 let page = $(`.page[data-page=${pageName}]`);25 if (shouldLoad === 0 || page.length == 0) {26 return;27 }28 await bsCheck(() => window.f7app);29 f7app.f7view.refreshPages();30 if (!shouldLoad) {31 f7app.f7view.router.back({});32 } else {33 f7app.f7view.router.load({ pageName });34 }35 }));36 };37}38export function changeset(prop) {39 return function(target, key, desc) {40 return {41 ...desc,42 initializer() {43 return computed.call(null, prop, function() {44 return new Changeset(this.get(prop));45 });46 }47 };48 };...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const params = await page._client.send('Page.getInstallabilityErrors');8 console.log(params);9 await browser.close();10 }11})();12{ errors: [] }13{ errors: [] }14{ errors: [] }15const playwright = require('playwright');16(async () => {17 for (const browserType of BROWSER) {18 const browser = await playwright[browserType].launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 const params = await page._client.send('Page.getInstallabilityErrors');22 console.log(params);23 await browser.close();24 }25})();26{ errors: [] }27{ errors: [] }28{ errors: [] }

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const {chromium} = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const params = await page._client.send('Page.getNavigationHistory');8 console.log(params.entries[params.currentIndex].url);9 await browser.close();10})();11const path = require('path');12const {chromium} = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const params = await page._client.send('Page.getNavigationHistory');18 console.log(params.entries[params.currentIndex].url);19 await browser.close();20})();21const path = require('path');22const {chromium} = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 const params = await page._client.send('Page.getNavigationHistory');28 console.log(params.entries[params.currentIndex].url);29 await browser.close();30})();31const path = require('path');32const {chromium} = require('playwright');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 const params = await page._client.send('Page.getNavigationHistory');38 console.log(params.entries[params.currentIndex].url);39 await browser.close();40})();41const path = require('path');42const {chromium} = require('playwright');43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext();46 const page = await context.newPage();47 await page.goto('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { paramsName } = require('@playwright/test');2const { test } = require('@playwright/test');3test('test', async ({ page }) => {4 await page.click(paramsName('Get Started'));5});6 at ElementHandle._assertBoundingBox (/Users/anuragsharma/Projects/playwright-test/node_modules/playwright-core/lib/cjs/pw-api.js:1227:15)7 at ElementHandle.click (/Users/anuragsharma/Projects/playwright-test/node_modules/playwright-core/lib/cjs/pw-api.js:1260:19)8 1 passed (1s)9 6: test('test', async ({ page }) => {10 8: await page.click(paramsName('Get Started'));

Full Screen

Using AI Code Generation

copy

Full Screen

1const { paramsName } = require('playwright/lib/utils/utils');2console.log(paramsName('test', 'test'));3const { paramsName } = require('playwright/lib/utils/utils');4console.log(paramsName('test', 'test'));5const { paramsName } = require('playwright/lib/utils/utils');6console.log(paramsName('test', 'test'));7const { paramsName } = require('playwright/lib/utils/utils');8console.log(paramsName('test', 'test'));9const { paramsName } = require('playwright/lib/utils/utils');10console.log(paramsName('test', 'test'));11const { paramsName } = require('playwright/lib/utils/utils');12console.log(paramsName('test', 'test'));13const { paramsName } = require('playwright/lib/utils/utils');14console.log(paramsName('test', 'test'));15const { paramsName } = require('playwright/lib/utils/utils');16console.log(paramsName('test', 'test'));17const { paramsName } = require('playwright/lib/utils/utils');18console.log(paramsName('test', 'test'));19const { paramsName } = require('playwright/lib/utils/utils');20console.log(paramsName('test', 'test'));

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful