Best JavaScript code snippet using redwood
query.unit.test.js
Source:query.unit.test.js
...4 const query = {5 };6 const result = {7 };8 expect(parseQuery(query)).toEqual(result);9 });10 test('compound query', () => {11 const query = {12 "occupations_group": ["Diplomacy", "Clergy"], "pursuits": ["diplomat"]13 };14 expect(parseQuery(query)).toMatchSnapshot();15 });16 test('query with object', () => {17 const query = {18 "occupations_group": [{ "_id": "Diplomacy" }]19 };20 expect(parseQuery(query)).toMatchSnapshot();21 });22 test('single query with string - should give fuzzy search', () => {23 const query = {24 "occupations_group": "Diplomacy"25 };26 expect(parseQuery(query)).toMatchSnapshot();27 });28 test('negative query', () => {29 const query = {30 "occupations_group": [{ "_id": "Diplomacy", "negative": true }, "Clergy"], "pursuits": ["diplomat"]31 };32 expect(parseQuery(query)).toMatchSnapshot();33 });34 test('empty query with OR', () => {35 const query = {36 "pursuits": { "operator": "or", "uniques": [] }37 };38 const result = {39 };40 expect(parseQuery(query)).toEqual(result);41 });42 test('query OR with object', () => {43 const query = {44 "occupations_group": { "operator": "or", "uniques": [{ "_id": "Diplomacy" }] }45 };46 expect(parseQuery(query)).toMatchSnapshot();47 });48 test('query AND with object', () => {49 const query = {50 "occupations_group": { "operator": "and", "uniques": [{ "_id": "Diplomacy" }, { "_id": "Democracy" }] }51 };52 expect(parseQuery(query)).toMatchSnapshot();53 });54 test('negative OR query', () => {55 const query = {56 "occupations_group": { "operator": "or", "uniques": [{ "_id": "Diplomacy", "negative": true }, { "_id": "Clergy" }] },57 "pursuits": { "operator": "or", "uniques": [{ "_id": "diplomat" }] }58 };59 expect(parseQuery(query)).toMatchSnapshot();60 });61 test('negative array (fullName and alternateNames) query', () => {62 const query = {63 "fullName": { "operator": "and", "uniques": [{ "_id": "John Taylor", "negative": true }] },64 };65 expect(parseQuery(query)).toMatchSnapshot();66 });67});68describe('test parseQuery with freeSearch', () => {69 test('regular freeSearch query', () => {70 const query = {71 "entry": {72 "terms": [73 {74 "value": "two",75 "beginning": true,76 "end": true,77 "negative": false78 },79 {80 "value": "three",81 "beginning": true,82 "end": true,83 "negative": false84 }85 ],86 "sections": [87 {88 "key": "biography",89 "name": "Biography",90 "checked": true91 },92 {93 "key": "narrative",94 "name": "Narrative",95 "checked": true96 },97 {98 "key": "tours",99 "name": "Tours",100 "checked": true101 },102 {103 "key": "notes",104 "name": "Notes",105 "checked": true106 }107 ],108 "operator": "or"109 }110 };111 expect(parseQuery(query)).toMatchSnapshot();112 });113 test('freeSearch query with "and" operator', () => {114 const query = {115 "entry": {116 "terms": [117 {118 "value": "two",119 "beginning": true,120 "end": true,121 "negative": false122 },123 {124 "value": "three",125 "beginning": true,126 "end": true,127 "negative": false128 }129 ],130 "sections": [131 {132 "key": "biography",133 "name": "Biography",134 "checked": true135 },136 {137 "key": "narrative",138 "name": "Narrative",139 "checked": true140 },141 {142 "key": "tours",143 "name": "Tours",144 "checked": true145 },146 {147 "key": "notes",148 "name": "Notes",149 "checked": true150 }151 ],152 "operator": "and"153 }154 };155 expect(parseQuery(query)).toMatchSnapshot();156 });157 test('freeSearch query with negatives', () => {158 const query = {159 "entry": {160 "terms": [161 {162 "value": "two",163 "beginning": true,164 "end": true,165 "negative": true166 },167 {168 "value": "three",169 "beginning": true,170 "end": true171 }172 ],173 "sections": [174 {175 "key": "biography",176 "name": "Biography",177 "checked": true178 },179 {180 "key": "narrative",181 "name": "Narrative",182 "checked": true183 },184 {185 "key": "tours",186 "name": "Tours",187 "checked": true188 },189 {190 "key": "notes",191 "name": "Notes",192 "checked": true193 }194 ]195 }196 };197 expect(parseQuery(query)).toMatchSnapshot();198 });199});200describe("test parseQuery with dates", () => {201 test("month range", () => {202 const query = {203 travelDate: {204 startMonth: "1",205 endMonth: "1"206 }207 };208 expect(parseQuery(query)).toMatchSnapshot();209 });210 test("single month", () => {211 const query = {212 travelDate: {213 startMonth: "1"214 }215 };216 expect(parseQuery(query)).toMatchSnapshot();217 });218 test("single year", () => {219 const query = {220 travelDate: {221 startYear: "1700"222 }223 };224 expect(parseQuery(query)).toMatchSnapshot();225 });226 test("single year and single month", () => {227 const query = {228 travelDate: {229 startYear: "1700",230 startMonth: "5"231 }232 };233 expect(parseQuery(query)).toMatchSnapshot();234 });235 test("year range", () => {236 const query = {237 travelDate: {238 startYear: "1700",239 endYear: "1780"240 }241 };242 expect(parseQuery(query)).toMatchSnapshot();243 });244 test("month range + year range", () => {245 const query = {246 travelDate: {247 startYear: "1700",248 endYear: "1780",249 startMonth: "1",250 endMonth: "10"251 }252 };253 expect(parseQuery(query)).toMatchSnapshot();254 });255 test("month range + single year", () => {256 const query = {257 travelDate: {258 startYear: "1700",259 startMonth: "1",260 endMonth: "10"261 }262 };263 expect(parseQuery(query)).toMatchSnapshot();264 });265 describe("repeated years/months should be treated the same as a single year/month", () => {266 describe("startYear", () => {267 expect(parseQuery({268 travelDate: {269 startYear: "1700",270 }271 })).toEqual(parseQuery({272 travelDate: {273 startYear: "1700",274 endYear: "1700"275 }276 }));277 });278 describe("startMonth", () => {279 expect(parseQuery({280 travelDate: {281 startMonth: "5"282 }283 })).toEqual(parseQuery({284 travelDate: {285 startMonth: "5",286 endMonth: "5"287 }288 }));289 });290 describe("startYear + startMonth", () => {291 expect(parseQuery({292 travelDate: {293 startYear: "1700",294 startMonth: "5",295 }296 })).toEqual(parseQuery({297 travelDate: {298 startYear: "1700",299 endYear: "1700",300 startMonth: "5",301 endMonth: "5"302 }303 }));304 });305 });306 test("date + place", () => {307 const query = {308 travelDate: {309 startYear: "1700",310 startMonth: "1",311 endMonth: "10"312 },313 travelPlace: {"operator":"and","uniques":[{"negative":false,"_id":"Genoa"}]}314 };315 expect(parseQuery(query)).toMatchSnapshot();316 });317 test("date + negative place", () => {318 const query = {319 travelDate: {320 startYear: "1700",321 startMonth: "1",322 endMonth: "10"323 },324 travelPlace: {"operator":"and","uniques":[{"negative":true,"_id":"Genoa"}]}325 };326 expect(parseQuery(query)).toMatchSnapshot();327 });...
filter.js
Source:filter.js
1const mqg = require("mongo-query-generator")2export const SENTENCE_REGEX = new RegExp(3 /[a-z0-9]*:(((NOT:))*"[^&()|"]+"|true|false)/gi4)5export const generateFilterQuery = (keyRef, values, noUnion) => {6 const queryList = Object.entries(values).reduce((acc, [name, value]) => {7 if (!value) return acc8 if (!keyRef[name]) return acc9 if (name === "dateFrom") {10 const { dateFrom, dateTo } = values11 if (dateFrom && dateTo) {12 acc.push(`${[keyRef["date"]]}=${dateFrom};${dateTo}`)13 } else if (dateFrom) {14 acc.push(`${[keyRef["date"]]}=${dateFrom};${new Date()}`)15 } else if (dateTo) {16 acc.push(`${[keyRef["date"]]}=${new Date()};${dateTo}`)17 }18 return acc19 }20 if (name === "dateTo") return acc21 if (name === "opened") {22 acc.push(`${[keyRef[name]]}=false`)23 return acc24 }25 if (Array.isArray(value)) {26 value.forEach((v) => {27 if (v.value !== "") {28 acc.push(`${[keyRef[name]]}=${v.value}`)29 }30 })31 return acc32 }33 if (typeof value === "object") {34 if (value?.value !== "") {35 acc.push(`${[keyRef[name]]}=${value.value}`)36 return acc37 }38 return acc39 }40 acc.push(`${[keyRef[name]]}=${value}`)41 return acc42 }, [])43 if (!noUnion) queryList.push("union=true")44 const filter = queryList.join("&")45 return filter46}47export const COMPLEX_OBJECT = {48 NOTES: "notes",49 TEST_SYSTEMS: "testSystmems",50 PROJECTS: "projects"51}52const ALIAS = {53 [COMPLEX_OBJECT.NOTES]: [54 "AliasCL",55 "AliasProy",56 "RefProy",57 "RefSis",58 "AliasSis",59 "Cerrado",60 "Formalizado",61 "Respuestas",62 "TagAp",63 "TagProy",64 "RefAp",65 "TitleAp",66 "Description",67 "Documents",68 "VtiCode"69 ],70 [COMPLEX_OBJECT.TEST_SYSTEMS]: [71 "TagAp",72 "TagProy",73 "AliasProy",74 "AliasSis",75 "AliasFocusPoint",76 "RefProy",77 "RefSis",78 "VtiCode",79 "RefAp",80 "TitleAp",81 "Sector",82 "Year",83 "Closed",84 "AliasCl"85 ],86 [COMPLEX_OBJECT.PROJECTS]: [87 "TagAp",88 "TagProy",89 "AliasProy",90 "AliasSis",91 "AliasFocusPoint",92 "RefProy",93 "RefSis",94 "VtiCode",95 "RefAp",96 "TitleAp",97 "Sector",98 "Year",99 "Closed",100 "AliasCl"101 ]102}103export const parseComplexQuery = (expression, object) => {104 if (!expression) {105 return { error: "La query no puede estar vacÃa" }106 }107 if (expression.includes(")(")) {108 return { error: 'No puede haber unión de paréntesis ")("' }109 }110 if (expression.match(/[(]/gi)?.length !== expression.match(/[)]/gi)?.length) {111 return { error: "Los parentesis de apertura y de cierre no son correctos" }112 }113 const queryConditionsCheck = ["(", ")", "&", "||", SENTENCE_REGEX]114 const error = queryConditionsCheck.reduce((str, condition) => {115 return str.replaceAll(condition, "")116 }, expression)117 if (error) {118 return { error: `Revisa esta sentencia: ${error}` }119 }120 const badCriterio = expression121 .match(/[a-z0-9]+:/gi)122 .map((cr) => cr.replace(":", ""))123 .filter((cr) => !ALIAS[object]?.includes(cr) && cr !== "NOT")124 if (badCriterio.length > 0) {125 return {126 error: `${127 badCriterio.length === 1 ? badCriterio[0] : badCriterio.join(", ")128 } no son criterios válidos`129 }130 }131 try {132 let _expression = expression133 // NOT134 _expression = _expression.replaceAll(":NOT:", "!==")135 _expression = _expression.replaceAll(":Not:", "!==")136 _expression = _expression.replaceAll(":not:", "!==")137 // EQUAL138 _expression = _expression.replaceAll(":", "===")139 // AND140 _expression = _expression.replaceAll("&", "&&")141 let query = mqg(_expression)142 let parseQuery = JSON.stringify(query)143 if (object === COMPLEX_OBJECT.NOTES) {144 parseQuery = parseQuery.replaceAll("AliasCL", "notes.clientAlias")145 parseQuery = parseQuery.replaceAll("AliasProy", "notes.projects.alias")146 parseQuery = parseQuery.replaceAll("RefProy", "notes.projects.ref")147 parseQuery = parseQuery.replaceAll("RefSis", "notes.testSystems.ref")148 parseQuery = parseQuery.replaceAll("AliasSis", "notes.testSystems.alias")149 parseQuery = parseQuery.replaceAll("Cerrado", "notes.isClosed")150 parseQuery = parseQuery.replaceAll("Formalizado", "notes.formalized")151 parseQuery = parseQuery.replaceAll("Respuestas", "notes.isAnswered")152 parseQuery = parseQuery.replaceAll("TagAp", "notes.tags.name")153 parseQuery = parseQuery.replaceAll("TagProy", "notes.projects.tags.name")154 parseQuery = parseQuery.replaceAll("RefAp", "notes.ref")155 parseQuery = parseQuery.replaceAll("TitleAp", "notes.title")156 parseQuery = parseQuery.replaceAll("Description", "notes.description")157 parseQuery = parseQuery.replaceAll("Documents", "notes.isDocuments")158 parseQuery = parseQuery.replaceAll("VtiCode", "notes.testSystems.vtiCode")159 } else if (object === COMPLEX_OBJECT.PROJECTS) {160 parseQuery = parseQuery.replaceAll("TagAp", "projects.notes.tags.name")161 parseQuery = parseQuery.replaceAll("TagProy", "projects.tags.name")162 parseQuery = parseQuery.replaceAll("AliasProy", "projects.alias")163 parseQuery = parseQuery.replaceAll("AliasSis", "projects.testSystems.alias")164 parseQuery = parseQuery.replaceAll(165 "AliasFocusPoint",166 "projects.focusPoint.alias"167 )168 parseQuery = parseQuery.replaceAll("RefProy", "projects.ref")169 parseQuery = parseQuery.replaceAll("RefSis", "projects.testSystems.ref")170 parseQuery = parseQuery.replaceAll("VtiCode", "projects.testSystems.vtiCode")171 parseQuery = parseQuery.replaceAll("RefAp", "projects.notes.ref")172 parseQuery = parseQuery.replaceAll("TitleAp", "projects.notes.title")173 parseQuery = parseQuery.replaceAll("Sector", "projects.sector.title")174 parseQuery = parseQuery.replaceAll("Year", "projects.date.year")175 parseQuery = parseQuery.replaceAll("Closed", "projects.isActive")176 parseQuery = parseQuery.replaceAll("AliasCl", "projects.clientAlias")177 } else {178 parseQuery = parseQuery.replaceAll("TagAp", "testSystems.notes.tags.name")179 parseQuery = parseQuery.replaceAll("TagProy", "testSystems.projects.tags.name")180 parseQuery = parseQuery.replaceAll("AliasProy", "testSystems.projects.alias")181 parseQuery = parseQuery.replaceAll("AliasSis", "testSystems.alias")182 parseQuery = parseQuery.replaceAll("TitleAp", "testSystems.title")183 parseQuery = parseQuery.replaceAll("RefProy", "testSystems.projects.ref")184 parseQuery = parseQuery.replaceAll("RefSis", "testSystems.ref")185 parseQuery = parseQuery.replaceAll("RefAp", "testSystems.notes.ref")186 parseQuery = parseQuery.replaceAll("Vticode", "testSystems.vtiCode")187 parseQuery = parseQuery.replaceAll("AliasCl", "testSystems.clientAlias")188 }189 return parseQuery190 } catch (error) {191 return {192 error:193 "Hay un error en la sintaxis de la consulta (revisa paréntesis y conectores)"194 }195 }...
parseQuery.spec.ts
Source:parseQuery.spec.ts
2import { mockWarn } from 'jest-mock-warn'3describe('parseQuery', () => {4 mockWarn()5 it('works with leading ?', () => {6 expect(parseQuery('?foo=a')).toEqual({7 foo: 'a',8 })9 })10 it('works without leading ?', () => {11 expect(parseQuery('foo=a')).toEqual({12 foo: 'a',13 })14 })15 it('works with an empty string', () => {16 const emptyQuery = parseQuery('')17 expect(Object.keys(emptyQuery)).toHaveLength(0)18 expect(emptyQuery).toEqual({})19 expect(parseQuery('?')).toEqual({})20 })21 it('decodes values in query', () => {22 expect(parseQuery('e=%25')).toEqual({23 e: '%',24 })25 })26 it('parses empty string values', () => {27 expect(parseQuery('e=&c=a')).toEqual({28 e: '',29 c: 'a',30 })31 })32 it('allows = inside values', () => {33 expect(parseQuery('e=c=a')).toEqual({34 e: 'c=a',35 })36 })37 it('parses empty values as null', () => {38 expect(parseQuery('e&b&c=a')).toEqual({39 e: null,40 b: null,41 c: 'a',42 })43 })44 it('parses empty values as null in arrays', () => {45 expect(parseQuery('e&e&e=a')).toEqual({46 e: [null, null, 'a'],47 })48 })49 it('decodes array values in query', () => {50 expect(parseQuery('e=%25&e=%22')).toEqual({51 e: ['%', '"'],52 })53 expect(parseQuery('e=%25&e=a')).toEqual({54 e: ['%', 'a'],55 })56 })57 it('decodes the + as space', () => {58 expect(parseQuery('a+b=c+d')).toEqual({59 'a b': 'c d',60 })61 })62 it('decodes the encoded + as +', () => {63 expect(parseQuery('a%2Bb=c%2Bd')).toEqual({64 'a+b': 'c+d',65 })66 })67 // this is for browsers like IE that allow invalid characters68 it('keep invalid values as is', () => {69 expect(parseQuery('e=%&e=%25')).toEqual({70 e: ['%', '%'],71 })72 expect('decoding "%"').toHaveBeenWarnedTimes(1)73 })...
Using AI Code Generation
1import { parseQuery } from '@redwoodjs/api'2export const handler = async (event, context) => {3 const { queryStringParameters } = event4 const parsed = parseQuery(queryStringParameters)5 return {6 body: JSON.stringify({ data: parsed }),7 }8}
Using AI Code Generation
1import { parseQuery } from '@redwoodjs/router'2import { useLocation } from '@redwoodjs/router'3const Test = () => {4 const location = useLocation()5 const query = parseQuery(location.search)6 return (7 <p>{query.name}</p>8}9<Route path="/test" page={TestPage} name="test" />
Using AI Code Generation
1import { parseQuery } from '@redwoodjs/router'2const Test = () => {3 const query = parseQuery(window.location.search)4 return (5 <p>{query.name}</p>6 <p>{query.age}</p>7}8To contribute to this project, please check out our [contributing guidelines](
Using AI Code Generation
1const { parseQuery } = require('@redwoodjs/api')2module.exports = (req, res) => {3 const query = parseQuery(req)4}5const { parseQuery } = require('@redwoodjs/api')6module.exports = (req, res) => {7 const query = parseQuery(req)8}9const { parseFilter } = require('@redwoodjs/api')10module.exports = (req, res) => {11 const filter = parseFilter(req)12}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!