graphQL vue this.$apollo.query doesn't work with parameter (variables) - vue.js

I have an application in Vuejs, and a function that downloads questionnaire via graphQL. Function works perfect until I add variables to the query.
The working code of function is:
downloadQuestionnaire() {
console.log("downloadQuestionnaire: " + questionnaireVersion);
this.$apollo
.query({
query: gql`
query questionnaire {
questionnaire(inputParams: { language: "en", version: 1 }) {
sections {
section
cssClass
remainingItemsType
endingMessageText
questions {
qId
label
question
inputType
possibleAnswers {
paId
text
}
multipleAnswersAccepted
individualFormat
answers
}
}
}
}
`,
client: "questionnaire",
variables: {
version: questionnaireVersion
}
})
.then(data => {
// this.sections = data.questionnaire;
// console.log(data);
this.copyQuestionnaie(data.data.questionnaire.sections);
// console.log(JSON.stringify(data.data.questionnaire.sections));
})
.catch(error => {
this.error = error;
alert("E " + error);
});
},
and I need to parametrise the version in the the query, by changing it to:
downloadQuestionnaire() {
console.log("downloadQuestionnaire: " + questionnaireVersion);
this.$apollo
.query({
query: gql`
query questionnaire($version: Int) {
questionnaire(
inputParams: { language: "en", version: $version }
) {
sections {
section
cssClass
remainingItemsType
endingMessageText
questions {
qId
label
question
inputType
possibleAnswers {
paId
text
}
multipleAnswersAccepted
individualFormat
answers
}
}
}
}
`,
client: "questionnaire",
variables: {
version: 1
}
})
.then(data => {
// this.sections = data.questionnaire;
// console.log(data);
this.copyQuestionnaie(data.data.questionnaire.sections);
// console.log(JSON.stringify(data.data.questionnaire.sections));
})
.catch(error => {
this.error = error;
alert("E " + error);
console.log("ERROR: " + error);
});
},
And then I get the error:
RROR: Error: Network error: Response not successful: Received status code 400
I was trying to use the same syntax as in example here.
Am I injecting the parameters in a wrong way or I oversee some typo?
Update:
Below is the schema python code for the backend:
import graphene
from .db import get_questionnaire_in_dict, getAnswers, putAnswers
class InputParam(graphene.InputObjectType): # type: ignore
"""Input parameters for questionnaire."""
language = graphene.String(required=True)
version = graphene.Int(required=True)
class PossibleAnswer(graphene.ObjectType): # type: ignore
"""Possible answers pair of key and text."""
paId = graphene.String(description="Answer id")
text = graphene.String(description="Answer text")
def __init__(self, paId: str, text: str) -> None:
self.paId = paId
self.text = text
def display(self) -> None:
"""Print self content."""
print("Label: {label},\nQuestion: {question}".format(
label=self.label, question=self.question))
class Question(graphene.ObjectType): # type: ignore
"""Question object."""
qId = graphene.String()
label = graphene.String(description="Translated question label")
question = graphene.String(description="Translated question")
# qPointer = graphene.Field(QuestionItems)
multipleAnswersAccepted = graphene.Boolean()
possibleAnswers = graphene.List(PossibleAnswer)
answers = graphene.List(graphene.String)
inputType = graphene.String(description="HTML input type")
individualFormat = graphene.String()
def __init__(self, questionObj):
self.qId = questionObj["qPointer"]
self.label = questionObj["label"]
self.question = questionObj["question"]
self.inputType = questionObj["inputType"]
self.multipleAnswersAccepted = questionObj["multipleAnswersAccepted"]
if "individualFormat" in questionObj:
self.individualFormat = questionObj["individualFormat"]
else:
self.individualFormat = None
if questionObj["possibleAnswersPointer"]:
self.possibleAnswers = []
for key, value in enumerate(questionObj["possibleAnswersPointer"]):
possibleAnswer = PossibleAnswer(key, value)
self.addPossibleAnswer(possibleAnswer)
else:
self.possibleAnswers = None
self.answers = []
def display(self):
print("Question {inputType}".format(inputType=self.inputType))
self.qPointer.display()
def addPossibleAnswer(self, possibleAnswer):
self.possibleAnswers.append(possibleAnswer)
class Section(graphene.ObjectType):
section = graphene.String()
css_class = graphene.String()
remainingItemsCount = graphene.Int
remainingItemsType = graphene.String()
endingMessageText = graphene.String()
questions = graphene.List(graphene.NonNull(Question))
def __init__(self, sectionObj):
self.section = sectionObj["section"]
self.css_class = sectionObj["class"]
self.remainingItemsCount = sectionObj["remainingItemsCount"]
self.remainingItemsType = sectionObj["remainingItemsType"]
self.endingMessageText = sectionObj["endingMessageText"]
self.questions = []
def display(self):
print("Section {section}, class: {css_class}".format(
section=self.section, css_class=self.css_class))
def addQuestion(self, question):
self.questions.append(question)
class Questionnaire(graphene.ObjectType): # type: ignore
lang = graphene.String()
sections = graphene.List(Section)
def __init__(self, lang):
self.lang = lang.language
self.sections = []
def addSection(self, section):
self.sections.append(section)
class AnswersInputParam(graphene.InputObjectType): # type: ignore
userId = graphene.String(required=True)
version = graphene.Int(required=True)
class Answer(graphene.ObjectType): # type: ignore
qId = graphene.String()
answers = graphene.List(graphene.String)
def __init__(self, answerObj):
print("Answer creator: {}".format(answerObj))
self.qId = answerObj["qId"]
self.answers = answerObj["answers"]
class Answers(graphene.ObjectType): # type: ignore
userId = graphene.String()
version = graphene.Int()
answers = graphene.List(Answer)
def __init__(self, answersObj, userId, version):
self.userId = userId
self.version = version
self.answers = []
# print("answersObj[\"answers\"]: {}".format(answersObj))
for index, value in enumerate(answersObj):
print("_XXX_: {idx}={val}".format(idx=index, val=value))
answer = Answer(value)
self.addAnswer(answer)
def addAnswer(self, answer):
self.answers.append(answer)
class SaveAnswers(graphene.Mutation):
class Arguments:
userId = graphene.String(required=True)
version = graphene.Int(required=True)
answers = graphene.JSONString(required=True)
Output = Answers
def mutate(self, info, answers, version, userId):
putAnswers(userId, version, answers)
return Answers(answers, userId, version)
class Mutation(graphene.ObjectType):
save_answers = SaveAnswers.Field()
class Query(graphene.ObjectType):
answers = graphene.Field(
Answers, inputParams=AnswersInputParam(required=True))
def resolve_answers(self, info, inputParams):
answers = getAnswers(inputParams.userId, inputParams.version)
return Answers(answers, inputParams.userId, inputParams.version)
questionnaire = graphene.Field(
Questionnaire, inputParams=InputParam(required=True))
def resolve_questionnaire(self, info, inputParams):
qest = Questionnaire(inputParams)
_struct = get_questionnaire_in_dict(
inputParams.language, inputParams.version)
for _sectionRef, sectionData in _struct.items():
s = Section(sectionObj=sectionData)
# s.display()
for key, value in sectionData.items():
# print(key, value)
if key == "questions":
for _questionNum, questionData in enumerate(value):
q = Question(questionObj=questionData)
# q.display()
s.addQuestion(question=q)
qest.addSection(s)
return qest
schema1 = graphene.Schema(query=Query, mutation=Mutation)
# sample calls
# mutation{
# saveAnswers
# (
# userId: "U123",
# version: 1,
# answers: "[{\"qId\":\"s1q4\",\"answers\":\"0\"},{\"qId\":\"s2q1\",\"answers\":\"1\"},{\"qId\":\"s2q10\",\"answers\":[\"1\",\"3\"]}]"
# ) {
# userId
# version
# answers {
# qId
# answers
# }
# }
# }
# {
# answers(inputParams: {userId: "U123", version: 1})
# {
# answers{
# qId
# answers
# }
# }
# }

Related

node_modules\react-native\react.gradle' line: 286

i am trying to build my app but i am getting error building it
errors are:
Task :app:bundleReleaseJsAndAssets FAILED
FAILURE: Build completed with 2 failures.
1: Task failed with an exception.
Where:
Script 'C:\Users\Ali Yousafzai\Desktop\ProjectFiver\BluetoothPlanner\node_modules\react-native\react.gradle' line: 286
What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
Process 'command 'cmd'' finished with non-zero exit value 1
2: Task failed with an exception.
What went wrong:
java.lang.StackOverflowError (no error message)
this is my react.gradle file
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.internal.jvm.Jvm
def config = project.hasProperty("react") ? project.react : [:];
def detectEntryFile(config) {
if (System.getenv('ENTRY_FILE')) {
return System.getenv('ENTRY_FILE')
} else if (config.entryFile) {
return config.entryFile
} else if ((new File("${projectDir}/../../index.android.js")).exists()) {
return "index.android.js"
}
return "index.js";
}
def composeSourceMapsPath = config.composeSourceMapsPath ?: "node_modules/react-native/scripts/compose-source-maps.js"
def bundleAssetName = config.bundleAssetName ?: "index.android.bundle"
def entryFile = detectEntryFile(config)
def bundleCommand = config.bundleCommand ?: "bundle"
def reactRoot = file(config.root ?: "../../")
def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"]
def bundleConfig = config.bundleConfig ? "${reactRoot}/${config.bundleConfig}" : null ;
def enableVmCleanup = config.enableVmCleanup == null ? true : config.enableVmCleanup
def hermesCommand = config.hermesCommand
/**
* Detects CLI location in a similar fashion to the React Native CLI
*/
def detectCliPath(config, reactRoot) {
// 1. preconfigured path
if (config.cliPath) {
def cliJsAbsolute = new File(config.cliPath)
if (cliJsAbsolute.exists()) {
return cliJsAbsolute.getAbsolutePath()
}
def cliJsRelativeToRoot = new File("${rootDir}/${config.cliPath}")
if (cliJsRelativeToRoot.exists()) {
return cliJsRelativeToRoot.getAbsolutePath()
}
def cliJsRelativeToProject = new File("${projectDir}/${config.cliPath}")
if (cliJsRelativeToProject.exists()) {
return cliJsRelativeToProject.getAbsolutePath()
}
}
// 2. node module path
def cliJsFromNode = new File(["node", "--print", "require.resolve('react-native/cli').bin"].execute(null, rootDir).text.trim())
if (cliJsFromNode.exists()) {
return cliJsFromNode.getAbsolutePath()
}
// 3. cli.js in the root folder
def rootCliJs = new File(reactRoot, "node_modules/react-native/cli.js")
if (rootCliJs.exists()) {
return rootCliJs.getAbsolutePath()
}
throw new Exception("Couldn't determine CLI location. " +
"Please set `project.ext.react.cliPath` to the path of the react-native cli.js file. " +
"This file typically resides in `node_modules/react-native/cli.js`");
}
def reactNativeDevServerPort() {
def value = project.getProperties().get("reactNativeDevServerPort")
return value != null ? value : "8081"
}
def reactNativeInspectorProxyPort() {
def value = project.getProperties().get("reactNativeInspectorProxyPort")
return value != null ? value : reactNativeDevServerPort()
}
def getHermesOSBin() {
if (Os.isFamily(Os.FAMILY_WINDOWS)) return "win64-bin";
if (Os.isFamily(Os.FAMILY_MAC)) return "osx-bin";
if (Os.isOs(null, "linux", "amd64", null)) return "linux64-bin";
throw new Exception("OS not recognized. Please set project.ext.react.hermesCommand " +
"to the path of a working Hermes compiler.");
}
// Make sure not to inspect the Hermes config unless we need it,
// to avoid breaking any JSC-only setups.
def getHermesCommand = {
// 1. If the project specifies a Hermes command, don't second guess it.
if (config.hermesCommand?.trim()) {
if (hermesCommand.contains("%OS-BIN%")) {
return hermesCommand
.replaceAll("%OS-BIN%", getHermesOSBin())
.replace('/' as char, File.separatorChar)
} else {
return hermesCommand
.replace('/' as char, File.separatorChar)
}
}
def hermescBin = Os.isFamily(Os.FAMILY_WINDOWS) ? 'hermesc.exe' : 'hermesc'
// 2. If the project is building hermes-engine from source, use hermesc from there
// Also note that user can override the hermes source location with
// the `REACT_NATIVE_OVERRIDE_HERMES_DIR` env variable.
def hermesOverrideDir = System.getenv("REACT_NATIVE_OVERRIDE_HERMES_DIR")
def builtHermesc = hermesOverrideDir ?
new File(hermesOverrideDir, "build/bin/$hermescBin") :
new File(reactRoot, "node_modules/react-native/ReactAndroid/hermes-engine/build/hermes/bin/$hermescBin")
if (builtHermesc.exists()) {
return builtHermesc.getAbsolutePath()
}
// 3. If the react-native contains a pre-built hermesc, use it.
def prebuiltHermesPath = "node_modules/react-native/sdks/hermesc/%OS-BIN%/$hermescBin"
.replaceAll("%OS-BIN%", getHermesOSBin())
.replace('/' as char, File.separatorChar);
def prebuiltHermes = new File(reactRoot, prebuiltHermesPath)
if (prebuiltHermes.exists()) {
return prebuiltHermes.getAbsolutePath()
}
throw new Exception("Couldn't determine Hermesc location. " +
"Please set `project.ext.react.hermesCommand` to the path of the hermesc binary file. " +
"node_modules/react-native/sdks/hermesc/%OS-BIN%/hermesc");
}
// Set enableHermesForVariant to a function to configure per variant,
// or set `enableHermes` to True/False to set all of them
def enableHermesForVariant = config.enableHermesForVariant ?: {
def variant -> config.enableHermes ?: false
}
// Set hermesFlagsForVariant to a function to configure per variant,
// or set `hermesFlagsRelease` and `hermesFlagsDebug` to an array
def hermesFlagsForVariant = config.hermesFlagsForVariant ?: {
def variant ->
def hermesFlags;
if (variant.name.toLowerCase().contains("release")) {
// Can't use ?: since that will also substitute valid empty lists
hermesFlags = config.hermesFlagsRelease
if (hermesFlags == null) hermesFlags = ["-O", "-output-source-map"]
} else {
hermesFlags = config.hermesFlagsDebug
if (hermesFlags == null) hermesFlags = []
}
return hermesFlags
}
// Set disableDevForVariant to a function to configure per variant,
// defaults to `devDisabledIn${targetName}` or True for Release variants and False for debug variants
def disableDevForVariant = config.disableDevForVariant ?: {
def variant ->
config."devDisabledIn${variant.name.capitalize()}" ||
variant.name.toLowerCase().contains("release")
}
// Set bundleForVariant to a function to configure per variant,
// defaults to `bundleIn${targetName}` or True for Release variants and False for debug variants
def bundleForVariant = config.bundleForVariant ?: {
def variant ->
config."bundleIn${variant.name.capitalize()}" ||
config."bundleIn${variant.buildType.name.capitalize()}" ||
variant.name.toLowerCase().contains("release")
}
// Set deleteDebugFilesForVariant to a function to configure per variant,
// defaults to True for Release variants and False for debug variants
def deleteDebugFilesForVariant = config.deleteDebugFilesForVariant ?: {
def variant -> variant.name.toLowerCase().contains("release")
}
android {
buildTypes.all {
resValue "integer", "react_native_dev_server_port", reactNativeDevServerPort()
resValue "integer", "react_native_inspector_proxy_port", reactNativeInspectorProxyPort()
}
}
def jvmVersion = Jvm.current().javaVersion.majorVersion
if (jvmVersion.toInteger() <= 8) {
println "\n\n\n"
println "**************************************************************************************************************"
println "\n\n"
println "ERROR: requires JDK11 or higher."
println "Incompatible major version detected: '" + jvmVersion + "'"
println "\n\n"
println "**************************************************************************************************************"
println "\n\n\n"
System.exit(1)
}
afterEvaluate {
def isAndroidLibrary = plugins.hasPlugin("com.android.library")
def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
variants.all { def variant ->
// Create variant and target names
def targetName = variant.name.capitalize()
def targetPath = variant.dirName
// React js bundle directories
def jsBundleDir = file("$buildDir/generated/assets/react/${targetPath}")
def resourcesDir = file("$buildDir/generated/res/react/${targetPath}")
def jsBundleFile = file("$jsBundleDir/$bundleAssetName")
def jsSourceMapsDir = file("$buildDir/generated/sourcemaps/react/${targetPath}")
def jsIntermediateSourceMapsDir = file("$buildDir/intermediates/sourcemaps/react/${targetPath}")
def jsPackagerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.packager.map")
def jsCompilerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.compiler.map")
def jsOutputSourceMapFile = file("$jsSourceMapsDir/${bundleAssetName}.map")
// Additional node and packager commandline arguments
def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]
def cliPath = detectCliPath(config, reactRoot)
def execCommand = []
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
execCommand.addAll(["cmd", "/c", *nodeExecutableAndArgs, cliPath])
} else {
execCommand.addAll([*nodeExecutableAndArgs, cliPath])
}
def enableHermes = enableHermesForVariant(variant)
def currentBundleTask = tasks.create(
name: "bundle${targetName}JsAndAssets",
type: Exec) {
group = "react"
description = "bundle JS and assets for ${targetName}."
// Create dirs if they are not there (e.g. the "clean" task just ran)
doFirst {
jsBundleDir.deleteDir()
jsBundleDir.mkdirs()
resourcesDir.deleteDir()
resourcesDir.mkdirs()
jsIntermediateSourceMapsDir.deleteDir()
jsIntermediateSourceMapsDir.mkdirs()
jsSourceMapsDir.deleteDir()
jsSourceMapsDir.mkdirs()
}
// Set up inputs and outputs so gradle can cache the result
inputs.files fileTree(dir: reactRoot, excludes: inputExcludes)
outputs.dir(jsBundleDir)
outputs.dir(resourcesDir)
// Set up the call to the react-native cli
workingDir(reactRoot)
// Set up dev mode
def devEnabled = !disableDevForVariant(variant)
def extraArgs = []
if (bundleConfig) {
extraArgs.add("--config")
extraArgs.add(bundleConfig)
}
// Hermes doesn't require JS minification.
if (enableHermes && !devEnabled) {
extraArgs.add("--minify")
extraArgs.add("false")
}
if (config.extraPackagerArgs) {
extraArgs.addAll(config.extraPackagerArgs)
}
commandLine(*execCommand, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
"--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
"--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
if (enableHermes) {
doLast {
def hermesFlags = hermesFlagsForVariant(variant)
def hbcTempFile = file("${jsBundleFile}.hbc")
exec {
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine("cmd", "/c", getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
} else {
commandLine(getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
}
}
ant.move(
file: hbcTempFile,
toFile: jsBundleFile
);
if (hermesFlags.contains("-output-source-map")) {
ant.move(
// Hermes will generate a source map with this exact name
file: "${jsBundleFile}.hbc.map",
tofile: jsCompilerSourceMapFile
);
exec {
// TODO: set task dependencies for caching
// Set up the call to the compose-source-maps script
workingDir(reactRoot)
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine("cmd", "/c", *nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
} else {
commandLine(*nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
}
}
}
}
}
enabled bundleForVariant(variant)
}
// Expose a minimal interface on the application variant and the task itself:
variant.ext.bundleJsAndAssets = currentBundleTask
currentBundleTask.ext.generatedResFolders = files(resourcesDir).builtBy(currentBundleTask)
currentBundleTask.ext.generatedAssetsFolders = files(jsBundleDir).builtBy(currentBundleTask)
// registerGeneratedResFolders for Android plugin 3.x
if (variant.respondsTo("registerGeneratedResFolders")) {
variant.registerGeneratedResFolders(currentBundleTask.generatedResFolders)
} else {
variant.registerResGeneratingTask(currentBundleTask)
}
variant.mergeResourcesProvider.get().dependsOn(currentBundleTask)
// packageApplication for Android plugin 3.x
def packageTask = variant.hasProperty("packageApplication")
? variant.packageApplicationProvider.get()
: tasks.findByName("package${targetName}")
if (variant.hasProperty("packageLibrary")) {
packageTask = variant.packageLibrary
}
// pre bundle build task for Android plugin 3.2+
def buildPreBundleTask = tasks.findByName("build${targetName}PreBundle")
def resourcesDirConfigValue = config."resourcesDir${targetName}"
if (resourcesDirConfigValue) {
def currentCopyResTask = tasks.create(
name: "copy${targetName}BundledResources",
type: Copy) {
group = "react"
description = "copy bundled resources into custom location for ${targetName}."
from(resourcesDir)
into(file(resourcesDirConfigValue))
dependsOn(currentBundleTask)
enabled(currentBundleTask.enabled)
}
packageTask.dependsOn(currentCopyResTask)
if (buildPreBundleTask != null) {
buildPreBundleTask.dependsOn(currentCopyResTask)
}
}
def currentAssetsCopyTask = tasks.create(
name: "copy${targetName}BundledJs",
type: Copy) {
group = "react"
description = "copy bundled JS into ${targetName}."
from(jsBundleDir)
if (config."jsBundleDir${targetName}") {
into(file(config."jsBundleDir${targetName}"))
} else {
into ("$buildDir/intermediates")
if (isAndroidLibrary) {
into ("library_assets/${variant.name}/out")
} else {
into ("assets/${targetPath}")
// Workaround for Android Gradle Plugin 3.2+ new asset directory
into ("merged_assets/${variant.name}/merge${targetName}Assets/out")
// Workaround for Android Gradle Plugin 3.4+ new asset directory
into ("merged_assets/${variant.name}/out")
// Workaround for Android Gradle Plugin 7.1 asset directory
into("$buildDir/intermediates/assets/${variant.name}/merge${targetName}Assets")
}
}
// mergeAssets must run first, as it clears the intermediates directory
dependsOn(variant.mergeAssetsProvider.get())
enabled(currentBundleTask.enabled)
dependsOn(currentBundleTask)
}
// mergeResources task runs before the bundle file is copied to the intermediate asset directory from Android plugin 4.1+.
// This ensures to copy the bundle file before mergeResources task starts
def mergeResourcesTask = tasks.findByName("merge${targetName}Resources")
mergeResourcesTask.dependsOn(currentAssetsCopyTask)
packageTask.dependsOn(currentAssetsCopyTask)
if (buildPreBundleTask != null) {
buildPreBundleTask.dependsOn(currentAssetsCopyTask)
}
// Delete the VM related libraries that this build doesn't need.
// The application can manage this manually by setting 'enableVmCleanup: false'
//
// This should really be done by packaging all Hermes related libs into
// two separate HermesDebug and HermesRelease AARs, but until then we'll
// kludge it by deleting the .so files out of the /transforms/ directory.
def cleanup = deleteDebugFilesForVariant(variant)
def vmSelectionAction = { libDir ->
fileTree(libDir).matching {
if (enableHermes) {
// For Hermes, delete all the libjsc* files
include "**/libjsc*.so"
if (cleanup) {
// Reduce size by deleting the debugger/inspector
include '**/libhermes-executor-debug.so'
} else {
// Release libs take precedence and must be removed
// to allow debugging
include '**/libhermes-executor-release.so'
}
} else {
// For JSC, delete all the libhermes* files
include "**/libhermes*.so"
}
}.visit { details ->
def targetVariant1 = ".*/transforms/[^/]*/${variant.name}/.*"
def targetVariant2 = ".*/merged_native_libs/${variant.name}/out/lib/.*"
def targetVariant3 = ".*/stripped_native_libs/${variant.name}/out/lib/.*"
def path = details.file.getAbsolutePath().replace(File.separatorChar, '/' as char)
if ((path.matches(targetVariant1) || path.matches(targetVariant2) || path.matches(targetVariant3)) && details.file.isFile()) {
details.file.delete()
}
}
}
if (enableVmCleanup) {
def task = tasks.findByName("package${targetName}")
if (task != null) {
def transformsLibDir = "$buildDir/intermediates/transforms/"
task.doFirst { vmSelectionAction(transformsLibDir) }
}
def sTask = tasks.findByName("strip${targetName}DebugSymbols")
if (sTask != null) {
def strippedLibDir = "$buildDir/intermediates/stripped_native_libs/${variant.name}/out/lib/"
sTask.doLast { vmSelectionAction(strippedLibDir) }
}
def mTask = tasks.findByName("merge${targetName}NativeLibs")
if (mTask != null) {
def mergedLibDir = "$buildDir/intermediates/merged_native_libs/${variant.name}/out/lib/"
mTask.doLast { vmSelectionAction(mergedLibDir) }
}
}
}
}
// Patch needed for https://github.com/facebook/react-native/issues/35210
// This is a patch to short-circuit the "+" dependencies inside the
// users' app/build.gradle file and the various .gradle files of libraries.
// As using plain "+" dependencies causes Gradle to always download the latest,
// this logic forces Gradle to use latest release in the minor series.
project.rootProject.allprojects {
configurations.all {
resolutionStrategy {
force "com.facebook.react:react-native:0.70.+"
force "com.facebook.react:hermes-engine:0.70.+"
}
}
}
I was in the same situation, the problem is when you have a space in the directory path.
This only happens on Windows + Hermes + folders that have a space in the path
For more details check this post
A quick fix is ​​to remove the space from the path
C:\Users\Ali Yousafzai\ -> C:\Users\AliYousafzai\
or
Just zip your project and move the file to a folder with no space
C:\yourproject

azurerm_mssql_virtual_machine - already exists

Trying to do an AZ Terraform deployment, and failing horribly - looking for some ideas what am I missing. Basically I am trying to deploy 2 (maybe later more) VM-s with variable size of disks, joining them to the domain and add SQL server to them. (Be gentle with me, I am from VMWare-Tf background, this is my first SQL deployment on AZ!)
My module:
## main.tf:
# ----------- NIC --------------------------------
resource "azurerm_network_interface" "nic" {
name = "${var.vm_name}-nic"
resource_group_name = var.rg.name
location = var.location
ip_configuration {
name = "${var.vm_name}-internal"
subnet_id = var.subnet_id
private_ip_address_allocation = "Static"
private_ip_address = var.private_ip
}
dns_servers = var.dns_servers
}
# ----------- VM --------------------------------
resource "azurerm_windows_virtual_machine" "vm" {
/* count = length(var.instances) */
name = var.vm_name
location = var.location
resource_group_name = var.rg.name
network_interface_ids = [azurerm_network_interface.nic.id]
size = var.size
zone = var.zone
admin_username = var.win_admin_user
admin_password = var.win_admin_pw # data.azurerm_key_vault_secret.vmadminpwd.value
enable_automatic_updates = "false"
patch_mode = "Manual"
provision_vm_agent = "true"
tags = var.vm_tags
source_image_reference {
publisher = "MicrosoftSQLServer"
offer = "sql2019-ws2019"
sku = "enterprise"
version = "latest"
}
os_disk {
name = "${var.vm_name}-osdisk"
caching = "ReadWrite"
storage_account_type = "StandardSSD_LRS"
disk_size_gb = 250
}
}
# ----------- DOMAIN JOIN --------------------------------
// Waits for up to 1 hour for the Domain to become available. Will return an error 1 if unsuccessful preventing the member attempting to join.
resource "azurerm_virtual_machine_extension" "wait-for-domain-to-provision" {
name = "TestConnectionDomain"
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.9"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
settings = <<SETTINGS
{
"commandToExecute": "powershell.exe -Command \"while (!(Test-Connection -ComputerName ${var.active_directory_domain_name} -Count 1 -Quiet) -and ($retryCount++ -le 360)) { Start-Sleep 10 } \""
}
SETTINGS
}
resource "azurerm_virtual_machine_extension" "join-domain" {
name = azurerm_windows_virtual_machine.vm.name
publisher = "Microsoft.Compute"
type = "JsonADDomainExtension"
type_handler_version = "1.3"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
settings = <<SETTINGS
{
"Name": "${var.active_directory_domain_name}",
"OUPath": "",
"User": "${var.active_directory_username}#${var.active_directory_domain_name}",
"Restart": "true",
"Options": "3"
}
SETTINGS
protected_settings = <<SETTINGS
{
"Password": "${var.active_directory_password}"
}
SETTINGS
depends_on = [azurerm_virtual_machine_extension.wait-for-domain-to-provision]
}
# ----------- DISKS --------------------------------
resource "azurerm_managed_disk" "data" {
for_each = var.disks
name = "${var.vm_name}-${each.value.name}"
location = var.location
resource_group_name = var.rg.name
storage_account_type = each.value.sa
create_option = each.value.create
disk_size_gb = each.value.size
zone = var.zone
}
resource "azurerm_virtual_machine_data_disk_attachment" "disk-attachment" {
for_each = var.disks
managed_disk_id = azurerm_managed_disk.data[each.key].id
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
lun = each.value.lun
caching = "ReadWrite"
depends_on = [azurerm_windows_virtual_machine.vm]
}
# ----------- SQL --------------------------------
# configure the SQL side of the deployment
resource "azurerm_mssql_virtual_machine" "sqlvm" {
/* count = length(var.instances) */
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
sql_license_type = "PAYG"
r_services_enabled = true
sql_connectivity_port = 1433
sql_connectivity_type = "PRIVATE"
/* sql_connectivity_update_username = var.sqladmin
sql_connectivity_update_password = data.azurerm_key_vault_secret.sqladminpwd.value */
#The storage_configuration block supports the following:
storage_configuration {
disk_type = "NEW" # (Required) The type of disk configuration to apply to the SQL Server. Valid values include NEW, EXTEND, or ADD.
storage_workload_type = "OLTP" # (Required) The type of storage workload. Valid values include GENERAL, OLTP, or DW.
data_settings {
default_file_path = "F:\\Data"
luns = [1]
}
log_settings {
default_file_path = "G:\\Log"
luns = [2]
}
temp_db_settings {
default_file_path = "D:\\TempDb"
luns = [0]
}
}
}
## provider.tf
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = ">=3.0.1"
#configuration_aliases = [azurerm.corp]
}
}
}
variables.tf
# ----------- COMMON --------------------------------
variable "vm_name" {
type = string
}
variable "rg" {
/* type = string */
description = "STACK - resource group"
}
variable "location" {
type = string
description = "STACK - location"
}
# ----------- NIC --------------------------------
variable "subnet_id" {
type = string
description = "STACK - subnet"
}
variable "private_ip" {
}
variable "dns_servers" {
}
# ----------- VM --------------------------------
variable "size" {
description = "VM - size"
type = string
}
variable "win_admin_user" {
sensitive = true
type = string
}
variable "win_admin_pw" {
sensitive = true
type = string
}
variable "os_storage_type" {
type = string
}
variable "vm_tags" {
type = map(any)
}
variable "zone" {
#type = list
description = "VM AZ"
}
# ----------- DOMAIN JOIN --------------------------------
variable "active_directory_domain_name" {
type = string
}
variable "active_directory_username" {
sensitive = true
}
variable "active_directory_password" {
sensitive = true
}
# ----------- SQL --------------------------------
variable "sql_maint_day" {
type = string
description = "SQL - maintenance day"
}
variable "sql_maint_length_min" {
type = number
description = "SQL - maintenance duration (min)"
}
variable "sql_maint_start_hour" {
type = number
description = "SQL- maintenance start (hour of the day)"
}
# ----------- DISKS --------------------------------
/* variable "disk_storage_account" {
type = string
default = "Standard_LRS"
description = "DATA DISKS - storage account type"
}
variable "disk_create_method" {
type = string
default = "Empty"
description = "DATA DISKS - creation method"
}
variable "disk_size0" {
type = number
}
variable "disk_size1" {
type = number
}
variable "disk_size2" {
type = number
}
variable "lun0" {
type = number
default = 0
}
variable "lun1" {
type = number
default = 1
}
variable "lun2" {
default = 2
type = number
} */
/* variable "disks" {
description = "List of disks to create"
type = map(any)
default = {
disk0 = {
name = "data0"
size = 200
create = "Empty"
sa = "Standard_LRS"
lun = 0
}
disk1 = {
name = "data1"
size = 500
create = "Empty"
sa = "Standard_LRS"
lun = 1
}
}
} */
variable "disks" {
type = map(object({
name = string
size = number
create = string
sa = string
lun = number
}))
}
the actual deployment:
main.tf
/*
PS /home/fabrice> Get-AzVMSize -Location northeurope | where-object {$_.Name -like "*ds13*"}
*/
module "uat_set" {
source = "../modules/vm"
providers = {
azurerm = azurerm.cbank-test
}
for_each = var.uat_set
active_directory_domain_name = local.uat_ad_domain
active_directory_password = var.domain_admin_password
active_directory_username = var.domain_admin_username
disks = var.disk_allocation
dns_servers = local.dns_servers
location = local.uat_location
os_storage_type = local.uat_storage_type
private_ip = each.value.private_ip
rg = data.azurerm_resource_group.main
size = each.value.vm_size
sql_maint_day = local.uat_sql_maintenance_day
sql_maint_length_min = local.uat_sql_maintenance_min
sql_maint_start_hour = local.uat_sql_maintenance_start_hour
subnet_id = data.azurerm_subnet.main.id
vm_name = each.key
vm_tags = var.default_tags
win_admin_pw = var.admin_password
win_admin_user = var.admin_username
zone = each.value.zone[0]
}
variable "uat_set" {
description = "List of VM-s to create"
type = map(any)
default = {
UAT-SQLDB-NE-01 = {
private_ip = "192.168.32.8"
vm_size = "Standard_DS13-4_v2"
zone = ["1"]
}
UAT-SQLDB-NE-02 = {
private_ip = "192.168.32.10"
vm_size = "Standard_DS13-4_v2"
zone = ["2"]
}
}
}
variable "disk_allocation" {
type = map(object({
name = string
size = number
create = string
sa = string
lun = number
}))
default = {
"temp" = {
name = "temp"
size = 200
create = "Empty"
sa = "Standard_LRS"
lun = 0
},
"disk1" = {
name = "data1"
size = 500
create = "Empty"
sa = "Standard_LRS"
lun = 1
},
"disk2" = {
name = "data2"
size = 500
create = "Empty"
sa = "Standard_LRS"
lun = 2
}
}
}
locals {
dns_servers = ["192.168.34.5", "192.168.34.10"]
uat_storage_type = "Standard_LRS"
uat_sql_maintenance_day = "Saturday"
uat_sql_maintenance_min = 180
uat_sql_maintenance_start_hour = 23
uat_ad_domain = "civbdev.local"
uat_location = "North Europe"
}
## variables.tf
# new build variables
variable "Environment" {
default = "DEV"
description = "this is the environment variable used to intperpolate with others vars"
}
variable "default_tags" {
type = map(any)
default = {
Environment = "DEV"
Product = "dev-XXXtemplateXXX"
Terraformed = "https://AllicaBankLtd#dev.azure.com/XXXtemplateXXX/Terraform/DEV"
}
}
variable "admin_username" {
sensitive = true
}
variable "admin_password" {
sensitive = true
}
variable "domain_admin_username" {
sensitive = true
}
variable "domain_admin_password" {
sensitive = true
}
Resources create OK, except the SQL-part
│ Error: A resource with the ID "/subscriptions/<..redacted...>/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/UAT-SQLDB-NE-02" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_mssql_virtual_machine" for more information.
│
│ with module.uat_set["UAT-SQLDB-NE-02"].azurerm_mssql_virtual_machine.sqlvm,
│ on ../modules/vm/main.tf line 115, in resource "azurerm_mssql_virtual_machine" "sqlvm":
│ 115: resource "azurerm_mssql_virtual_machine" "sqlvm" {
│
╵
╷
│ Error: A resource with the ID "/subscriptions/<..redacted...>/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/UAT-SQLDB-NE-01" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_mssql_virtual_machine" for more information.
│
│ with module.uat_set["UAT-SQLDB-NE-01"].azurerm_mssql_virtual_machine.sqlvm,
│ on ../modules/vm/main.tf line 115, in resource "azurerm_mssql_virtual_machine" "sqlvm":
│ 115: resource "azurerm_mssql_virtual_machine" "sqlvm" {
│
╵
Any notions please what I might be missing?
Ta,
Fabrice
UPDATE:
Thanks for those who replied. Just to confirm: it is not an already existing resource. I get this error straight at the time of the creation of these VM-s.
For example, these are my vm-s after the Terraform run (none of them has the sql extension)
Plan even states it will create these:
Terraform will perform the following actions:
# module.uat_set["UAT-SQLDB-NE-01"].azurerm_mssql_virtual_machine.sqlvm will be created
+ resource "azurerm_mssql_virtual_machine" "sqlvm" {
+ id = (known after apply)
+ r_services_enabled = true
+ sql_connectivity_port = 1433
+ sql_connectivity_type = "PRIVATE"
+ sql_license_type = "PAYG"
+ virtual_machine_id = "/subscriptions/..../providers/Microsoft.Compute/virtualMachines/UAT-SQLDB-NE-01"
+ storage_configuration {
+ disk_type = "NEW"
+ storage_workload_type = "OLTP"
+ data_settings {
+ default_file_path = "F:\\Data"
+ luns = [
+ 1,
]
}
+ log_settings {
+ default_file_path = "G:\\Log"
+ luns = [
+ 2,
]
}
+ temp_db_settings {
+ default_file_path = "Z:\\TempDb"
+ luns = [
+ 0,
]
}
}
}
# module.uat_set["UAT-SQLDB-NE-02"].azurerm_mssql_virtual_machine.sqlvm will be created
+ resource "azurerm_mssql_virtual_machine" "sqlvm" {
+ id = (known after apply)
+ r_services_enabled = true
+ sql_connectivity_port = 1433
+ sql_connectivity_type = "PRIVATE"
+ sql_license_type = "PAYG"
+ virtual_machine_id = "/subscriptions/..../providers/Microsoft.Compute/virtualMachines/UAT-SQLDB-NE-02"
+ storage_configuration {
+ disk_type = "NEW"
+ storage_workload_type = "OLTP"
+ data_settings {
+ default_file_path = "F:\\Data"
+ luns = [
+ 1,
]
}
+ log_settings {
+ default_file_path = "G:\\Log"
+ luns = [
+ 2,
]
}
+ temp_db_settings {
+ default_file_path = "Z:\\TempDb"
+ luns = [
+ 0,
]
}
}
}
Plan: 2 to add, 0 to change, 0 to destroy.
Presumably, if these resources would exist somehow - which would be odd, as Tf just created the VM-s - then it would not say in the plan that it will create it now, would it?
So the error is quite the source of my confusion, since if the VM just got created, the creation of the extension failed - how could it possibly be existing?
In this case you should probably just import the modules as the error suggest to your terraform state.
For example
terraform import module.uat_set[\"UAT-SQLDB-NE-02\"].azurerm_mssql_virtual_machine.sqlvm "/subscriptions/<..redacted...>/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/UAT-SQLDB-NE-02"

Looping over map variable using for_each expression in terraform

I have variable that I want to iterate over using for_each in terraform to create multiple instances of submodule - node_groups, which is part of eks module. This is my variable:
variable "frame_platform_eks_node_groups" {
type = map
default = {
eks_kube_system = {
desired_capacity = 1,
max_capacity = 5,
min_capacity = 1,
instance_type = ["m5.large"],
k8s_label = "eks_kube_system",
additional_tags = "eks_kube_system_node"
},
eks_jenkins_build = {
desired_capacity = 1,
max_capacity = 10,
min_capacity = 1,
instance_type = ["m5.large"],
k8s_label = "eks_jenkins_build",
additional_tags = "eks_jenkins_build_node"
}
}
}
And this is my node_groups submodule, which is part of module eks.
module "eks" {
...
node_groups = {
for_each = var.frame_platform_eks_node_groups
each.key = {
desired_capacity = each.value.desired_capacity
max_capacity = each.value.max_capacity
min_capacity = each.value.min_capacity
instance_types = each.value.instance_type
k8s_labels = {
Name = each.value.k8s_label
}
additional_tags = {
ExtraTag = each.value.additional_tags
}
}
When I run terraform plan I am getting following error:
15: each.key = {
If this expression is intended to be a reference, wrap it in parentheses. If
it’s instead intended as a literal name containing periods, wrap it in quotes
to create a string literal.
My intention obviously is to get eks_kube_system and eks_jenkins_build values from the map variable with each.key reference. But something is wrong. Do you have advice what I am doing wrong?
Thank you!
Its not exactly clear what node_groups is as it is not defined in your question, but assuming that it is a list of maps, then the code should be:
module "eks" {
...
node_groups = [
for k,v in var.frame_platform_eks_node_groups:
{
desired_capacity = v.desired_capacity
max_capacity = v.max_capacity
min_capacity = v.min_capacity
instance_types = v.instance_type
k8s_labels = {
Name = v.k8s_label
}
additional_tags = {
ExtraTag = v.additional_tags
}
}
]

Django channels without redis

I have a django app based on this tutorial that works perfectly. It uses Redis in the Channel layers
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
The problem I have is that my web hosting provider will not allow Redis (unless I pay ££££).
Every example that I can find uses Redis in this role. Is there an alternative I could use?
there are a few options.
you can run your channel layer on a different service to were the main instance runs. AWS ElastiCache or many other redis hosts out there.
There is also a RabbitMQ channel layer but if your hosting provider charges a lot for reddis i expect they will also charge a lot for this ... https://github.com/CJWorkbench/channels_rabbitmq/
It turned out that channels is a non-starter on an affordable web-hosting platform. So I reverted to using Ajax and long polling. My application is based on this Django Tutorial.
models.py
class Message(models.Model):
room_name = models.CharField(null=False, blank=False, max_length=50)
sender = models.CharField(null=False, blank=False, max_length=50, default='Sender username')
datetime = models.DateTimeField(null=True, auto_now_add=True)
type = models.IntegerField(null=True, blank=True)
text = models.CharField(null=False, blank=False, max_length=250, default='message text')
context = models.TextField(null=True, blank=True)
urls.py
urlpatterns = [
path('<str:partner_pk>/check-message', views.CheckMessage.as_view(), name="check-message"),
path('<str:partner_pk>/send-message/<str:chat_text>', views.SendMessage.as_view(), name="send-message"),
]
views.py
class CheckMessage(View):
"""Duo check message."""
def get(self, request, partner_pk):
"""Render the GET request."""
pair, room_name = sort_pair(partner_pk, request.user.pk)
partner = User.objects.get(pk=partner_pk)
profile = get_object_or_404(Profile, user=request.user)
message = Message.objects.filter(room_name=room_name, sender=partner.username).earliest('datetime')
context = {'type': -1}
context = json.loads(message.context)
context['sender'] = message.sender
context['datetime'] = message.datetime
context['message_type'] = message.type
context['text'] = message.text
context['seat'] = profile.seat
message.delete()
return JsonResponse(context, safe=False)
class SendMessage(View):
def get(self, request, partner_pk, chat_text):
message_type = app.MESSAGE_TYPES['chat']
send_message(request, partner_pk, message_type, text=chat_text, context={})
return JsonResponse({}, safe=False)
chat.js
window.setInterval(checkMessage, 3000);
function checkMessage () {
$.ajax(
{
type:"GET",
url: "check-message",
cache: false,
success: function(message) {
processMessage(message);
}
}
)
}
// Take action when a message is received
function processMessage(context) {
switch (context.message_type) {
case 0:
sendMessage(context)
functionOne()
break;
case 1:
sendMessage(context)
functionTwo()
break;
case 2:
sendMessage(context)
functionThree()
break;
}
}
// Send a message to chat
function sendMessage (context) {
if (context.sender != username) {
var messageObject = {
'username': context.sender,
'text': context.text,
};
displayChat(context);
}
}
// Display a chat message in the chat box.
function displayChat(context) {
if (context.text !== '') {
var today = new Date();
var hours = pad(today.getHours(), 2)
var minutes = pad(today.getMinutes(), 2)
var seconds = pad(today.getSeconds(), 2)
var time = hours + ":" + minutes + ":" + seconds;
var chat_log = document.getElementById("chat-log");
chat_log.value += ('('+time+') '+context.sender + ': ' + context.text + '\n');
chat_log.scrollTop = chat_log.scrollHeight;
}
}
//pad string with leading zeros
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
// Call submit chat message if the user presses <return>.
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function (e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
// Submit the chat message if the user clicks on 'Send'.
document.querySelector('#chat-message-submit').onclick = function (e) {
var messageField = document.querySelector('#chat-message-input'), text = messageField.value, chat_log = document.getElementById("chat-log");
context = {sender: username, text: messageField.value}
displayChat(context)
sendChat(messageField.value)
chat_log.scrollTop = chat_log.scrollHeight;
messageField.value = '';
};
// Call the send-chat view
function sendChat(chat_text) {
$.ajax(
{
type:"GET",
url: "send-message/"+chat_text,
cache: false,
}
)
}

Karate API : Converting two arrays into an object

How to merge to below arrays into an object in Karate API. I tried below code it is not working.
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
Feature: ArrayToObject
Scenario: ArrayToObject Coversion JS script
* def keys = ['foo', 'bar', 'qux']
* def values = ['1', '2', '3']
* def Arr2object =
"""
function (keys, vals) {
return keys.reduce(
function(prev, val, i) {
prev[val] = vals[i];
return prev;
}, {}
);
}
"""
* string text = Arr2object(keys, values)
* print text
Expected something like this
{
"foo": "1",
"bar": "2",
"qux": "3"
}
This might work,
* def Arr2object =
"""
function(keys,values){
var newObj = {};
if(keys.length == values.length){
for (var i = 0; i <= keys.length - 1; i++) {
newObj [keys[i]] = values[i];
}
return newObj;
}
return newObj;
}