Parsing Yaml file - parsing

For the last 3 days now, I tried to figure out how to parse my yaml in Rust.
And I can't figure out why it doesn't work.
My Yaml:
default_verbosity: 0
logging:
use_color: True,
log_color:
fatal: Red,
error: Red,
warn: Red,
info: Green,
debug: Blue,
trace: Yellow
log_output: file,
file_location: "example.log"
rocket:
mount_location: "/",
port: 8000
But my programm failes at the unwrap line: let myYaml: Config = serde_yaml::from_reader(yamlFile).unwrap(); with this error message:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
Scan(ScanError { mark: Marker { index: 284, line: 14, col: 21 }, info: "while parsing
a block mapping, did not find expected key" })', src/main.rs:41:60
My program:
use std::fs::File;
extern crate serde_yaml;
#[macro_use]
extern crate serde_derive;
#[derive(Debug, Serialize, Deserialize)]
struct ColorStruct {
fatal: String,
error: String,
warn: String,
info: String,
debug: String,
trace: String
}
#[derive(Debug, Serialize, Deserialize)]
struct LoggingStruct {
use_color: bool,
log_color: Vec<ColorStruct>,
log_output: String,
file_location: String
}
#[derive(Debug, Serialize, Deserialize)]
struct RocketStruct {
mount_location: String,
port: String
}
#[derive(Debug, Serialize, Deserialize)]
struct Config {
default_verbosity: i32,
logging: Vec<LoggingStruct>,
rocket: Vec<RocketStruct>
}
fn main(){
let yamlFile = File::open("config.yaml").unwrap();
let myYaml: Config = serde_yaml::from_reader(yamlFile).unwrap();
}
I am really frustrated by this. What am I doing wrong? Am I missing something in my structs?

Both your schema and your yaml were wrong. Main reasons:
You should have nested structs, not Vec.
Your yaml types were not accurate, for example True is string, true is bool. 8000 is not String, "8000" is.
use std::fs::File;
use serde_yaml; // 0.8.23
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
struct ColorStruct {
fatal: String,
error: String,
warn: String,
info: String,
debug: String,
trace: String
}
#[derive(Debug, Serialize, Deserialize)]
struct LoggingStruct {
use_color: bool,
log_color: ColorStruct,
log_output: String,
file_location: String
}
#[derive(Debug, Serialize, Deserialize)]
struct RocketStruct {
mount_location: String,
port: String
}
#[derive(Debug, Serialize, Deserialize)]
struct Config {
default_verbosity: i32,
logging: LoggingStruct,
rocket: RocketStruct
}
fn main(){
let yamlFile = r#"default_verbosity: 0
logging:
use_color: true
log_color:
fatal: "Red"
error: "Red"
warn: "Red"
info: "Green"
debug: "Blue"
trace: "Yellow"
log_output: "file"
file_location: "example.log"
rocket:
mount_location: "/"
port: "8000""#;
let myYaml: Config = serde_yaml::from_str(yamlFile).unwrap();
}
Playground
If you really want to use Vec as part of your original schema, you would need some changes:
Probably ColorStruct should be an enum, but if not you just need to keep as the remaining examples.
Your yaml need to provide the data correcly too to match those types.
#[derive(Debug, Serialize, Deserialize)]
enum ColorStruct {
fatal(String),
error(String),
warn(String),
info(String),
debug(String),
trace(String),
}
...
let yamlFile = r#"default_verbosity: 0
logging: [
{
log_output: "file",
file_location: "example.log",
use_color: true,
log_color: [
{ fatal: "Red" },
{ error: "Red" },
{ warn: "Red" },
{ info: "Green" },
{ debug: "Blue" },
{ trace: "Yellow" }
]
}
]
rocket: [
{
mount_location: "/",
port: "8000"
}
]"#;
...
Playground

Related

ktor dynamic keys serialization and json preprosesing

Is there anyway in Ktor to alter a json before deserialization process? In the example below there is a json with dynamic keys in which i need to remove the "token" key as it is of a string type instead of an object type as the other keys.
When i urn the code i get the following error:
Exception in thread "main" kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject as the serialized body of shell.remoting.Market, but had class kotlinx.serialization.json.JsonLiteral
I'm not sure if there is another better way to do it. Any suggestion will be appreciated, thanks
object MarketMapSerializer :
JsonTransformingSerializer<Map<String, Market>>(MapSerializer(String.serializer(), Market.serializer())) {
override fun transformSerialize(element: JsonElement): JsonElement =
JsonObject(element.jsonObject.filterNot { (k, _) ->
k == "token"
})
}
#Serializable
data class Market(
val stations: List<Station>,
)
#Serializable
data class Station(
#JsonNames("iata_code")
val iataCode: String,
val destinations: List<String>,
)
fun main() {
val jsonString = """
{
"Republica Dominicana": {
"stations": [
{
"iata_code": "PUJ",
"destinations": [
"ADZ",
"BAQ",
"VVC"
]
}
]
},
"Brasil": {
"stations": [
{
"iata_code": "AJO",
"destinations": [
"ADZ",
"BAQ",
"VVC"
]
}
]
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkb3RSRVogQVBJIiwianRpIjoiYTVhZDM4NmYtOGViNy0yOWQ5LWZkMGYtM2Q3MzQwZmRhOGI2IiwiaXNzIjoiZG90UkVaIEFQSSJ9.V2YfXCt9r7Tzae9SYSoj-qIyxjRc9YoE2XPoIQQNI9U"
}
""".trimIndent()
println(
Json.decodeFromString(
MarketMapSerializer,
jsonString
)
)
}
Just replace transformSerialize with the transformDeserialize since you're doing deserialization.

Apollo server, GraphQL and Sequelize - how to put raw data into a GraphQL Schema Response

After scouring the internet for a specific example, I am throwing in the towel and asking for some help.
I am using Apollo server, GraphQL and Sequelize, and I am calling stored procedure that returns a record set created from two different tables. I am getting the data back, but I cannot figure out how to put the result into a GraphQL schema response.
Here is the code in my resolver:
async functionName(_, {input}, {user = null}) {
if (!user) {
throw new AuthenticationError('You must login to use this function');
}
const {record_id} = input;
const result = await DBService.query(
'Call sp_JoinTwoTables_Select(:id)',
{
model: FooModel,
mapToModel: true,
raw: true,
replacements: {id: record_id},
type: QueryTypes.SELECT
}
);
console.log('functionName.result');
console.log(result); // Getting results
return result;
}
Here is the code in my schema:
const {gql} = require('apollo-server-express');
module.exports = gql`
type Foo {
id: Int!
foo_name: String!
date_created: String!
date_modified: String!
}
extend type Mutation {
functionName(input: fooInput!): fooResponse!
}
input fooInput {
id: Int!
}
type fooResponse {
tree: [fooSchemaForBothTables!]
}
type fooSchemaForBothTables {
id: Int!
foo_name: String!
column_from_second_table: Int!
}
`;
Since there is no table in the database, I created a simple object. When that failed I tried a sequelized model object, but that also is failing. Here is this code:
module.exports = {FooModel: {
id: 0,
fooName: '',
column_from_second_table: 0
}};
The output I am getting is (not a 2d array as I thought):
Executing (default): Call sp_CommunityHierarchy_Select(9)
selectHierarchyTree.result
[
{
'0': {
community_id: 1,
community_name: 'Cars',
level_from_apex: null,
parent_id: null
},
'1': {
community_id: 8,
community_name: 'Chevy',
level_from_apex: 2,
parent_id: 1
},
'2': {
community_id: 9,
community_name: 'Suburban',
level_from_apex: 3,
parent_id: 8
},
meta: [ [ColumnDef], [ColumnDef], [ColumnDef], [ColumnDef] ]
},
{ affectedRows: 6, insertId: 0, warningStatus: 0 }
]
Your 'raw' DB result:
is an array;
1st element is an object with records/items encoded as index-named properties;
Your required mutation (why not a query type!?) response should tree: [fooSchemaForBothTables!] - object with tree named property (really required additional nesting level?) with an array of fooSchemaForBothTables-shaped objects as values:
{
tree: [
{
id: 1,
foo_name: 'Cars`,
column_from_second_table: 'whatever`,
},
{
id: 2,
foo_name: 'Chevy`,
column_from_second_table: 'whatever`,
}
]
}
Your job is to convert DB response into the required mutation result shape.
Hint: You can hardcode this DB result (some input const) in a side project (codesandbox) and write some conversion fn. When ready use it in this resolver.
You can also search for some more reliable sequelize (leave graphql alone for a moment) tutorials with 'more working' model mapping.
Next step?
If it is a tree then why not return this as a tree structure - nested nodes/types?

Error: Unknown directive "relation". with Grand-stack of neo4j

I am trying grand-stack-starter from neo4j and getting the below error with API module after I do all the graphql schema part. it complains that directive 'relation' and 'cypher'are unknown.
I reinstalled neo4j-graphql-js but didnt solve the problem.
Below is the error message
grand-stack-starter-api#0.0.1 start C:\Users\grand-stack-starter-master\api
nodemon --exec babel-node src/index.js
[nodemon] 1.18.9
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting babel-node src/index.js
C:\Users\grand-stack-starter-master\api\node_modules\graphql\validation\validate.js:89
throw new Error(errors.map(function (error) {
^
Error: Unknown directive "relation".
Unknown directive "relation".
Unknown directive "cypher".
Unknown directive "cypher".
Unknown directive "relation".
Unknown directive "relation".
Unknown directive "relation".
Unknown directive "relation".
Unknown directive "relation".
Unknown directive "cypher".
at assertValidSDL (C:\Users\N19683\grand-stack-starter-master\api\node_modules\graphql\validation\validate.js:89:11)
at Object.buildASTSchema (C:\Users\N19683\grand-stack-starter-master\api\node_modules\graphql\utilities\buildASTSchema.js:67:34)
at Object.buildSchemaFromTypeDefinitions (C:\Users\N19683\grand-stack-starter-master\api\node_modules\graphql-tools\src\generate\buildSchemaFromTypeDefinitions.ts:43:32)
at makeExecutableSchema (C:\Users\N19683\grand-stack-starter-master\api\node_modules\graphql-tools\src\makeExecutableSchema.ts:52:16)
at Object.<anonymous> (C:/Users/N19683/grand-stack-starter-master/api/src/index.js:18:16)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at loader (C:\Users\N19683\grand-stack-starter-master\api\node_modules\babel-register\lib\node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (C:\Users\N19683\grand-stack-starter-master\api\node_modules\babel-register\lib\node.js:154:7)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
**
Below is the graphql-schema.js
import { neo4jgraphql } from "neo4j-graphql-js";
export const typeDefs = `
type User {
id: ID!
name: String
friends: [User] #relation(name: "FRIENDS", direction: "BOTH")
reviews: [Review] #relation(name: "WROTE", direction: "OUT")
avgStars: Float
#cypher(
statement: "MATCH (this)-[:WROTE]->(r:Review) RETURN toFloat(avg(r.stars))"
)
numReviews: Int
#cypher(statement: "MATCH (this)-[:WROTE]->(r:Review) RETURN COUNT(r)")
}
type Business {
id: ID!
name: String
address: String
city: String
state: String
reviews: [Review] #relation(name: "REVIEWS", direction: "IN")
categories: [Category] #relation(name: "IN_CATEGORY", direction: "OUT")
}
type Review {
id: ID!
stars: Int
text: String
date: Date
business: Business #relation(name: "REVIEWS", direction: "OUT")
user: User #relation(name: "WROTE", direction: "IN")
}
type Category {
name: ID!
businesses: [Business] #relation(name: "IN_CATEGORY", direction: "IN")
}
type Query {
usersBySubstring(substring: String): [User]
#cypher(
statement: "MATCH (u:User) WHERE u.name CONTAINS $substring RETURN u"
)
}
`
export const resolvers = {
Query: {
Users: neo4jgraphql,
Business: neo4jgraphql,
Category: neo4jgraphql,
Review: neo4jgraphql
}
};
index.js
import { typeDefs, resolvers } from "./graphql-schema";
import { ApolloServer, gql, makeExecutableSchema } from "apollo-server";
import { v1 as neo4j } from "neo4j-driver";
import { augmentSchema } from "neo4j-graphql-js";
import dotenv from "dotenv";
// set environment variables from ../.env
dotenv.config();
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
const augmentedSchema = augmentSchema(schema);
const driver = neo4j.driver(
process.env.NEO4J_URI || "bolt://localhost:7689",
neo4j.auth.basic(
process.env.NEO4J_USER || "neo4j",
process.env.NEO4J_PASSWORD || "letmein"
)
);
const server = new ApolloServer({
context: { driver },
schema: augmentedSchema
});
server.listen(process.env.GRAPHQL_LISTEN_PORT, "0.0.0.0").then(({ url }) => {
console.log(`GraphQL API ready at ${url}`);
});
Can anyone please help to fix the issue! Thanks in advance
As noted in the docs
NOTE: Only use augmentSchema if you are working with an existing GraphQLSchema object. In most cases you should use makeAugmentedSchema which can construct the GraphQLSchema object from type definitions.
The error is occurring because you're attempting to use makeExecutableSchema to create your schema. The #relation and #cypher directives are used exclusively by neo4j-graphql. Since they're not actually defined as part of your schema, building your schema with makeExecutableSchema will result in an error just like using any other undefined directive.
You should just use makeAugmentedSchema instead:
const schema = makeAugmentedSchema({
typeDefs,
resolvers,
})
const driver = /* ... */
const server = new ApolloServer({
context: { driver },
schema,
})

Why does "run seedDb" fail when I add in relations between nodes moving from graphql to neo4j

I got the demo example from grand-stack and was able to start up graphql, start up the Neo4J sandbox and populate the test database using
npm run seedDb
However, when I try to write my own data entries to populate into a neo4j database, I cannot get the relation between nodes to work at all. The error message is the most non-useful message (and I believe it is from the apollo client, and is a status code 400 error). I simplified the code to the most simplest case to make it work, and it still does not. Here is the schema.graphql file:
type Patient {
id: ID!
name: String
reviews: [Review] #relation(name:"WROTE", direction:"OUT")
}
type Review {
id: ID!
stars: Int
text: String
date: Date
user: Patient #relation(name: "WROTE", direction: "IN")
}
and here is the seed-mutation.js file:
export default /* GraphQL */ `
mutation {
p1: CreatePatient(
id: "p1",
name: "John Doe 1"
) {
id
name
}
r1: CreateReview(id: "r1", stars: 4, text: "Great IPA selection!", date: { formatted: "2016-01-03"}) {
id
}
ar1: AddUserReviews(from: { id: "p1"}, to: { id: "r1" }) { from {id}}
}
`;
When I do "npm run seedDb", this yields the error message:
{ Error: Network error: Response not successful: Received status code 400
at new ApolloError (/Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/apollo-client/bundle.esm.js:60:28)
at Object.error (/Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/apollo-client/bundle.esm.js:1032:48)
at notifySubscription (/Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/zen-observable/lib/Observable.js:134:18)
at onNotify (/Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/zen-observable/lib/Observable.js:165:3)
at SubscriptionObserver.error (/Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/zen-observable/lib/Observable.js:224:7)
at /Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/apollo-link-http/src/httpLink.ts:184:20
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
graphQLErrors: [],
networkError:
{ ServerError: Response not successful: Received status code 400
at Object.exports.throwServerError (/Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/apollo-link-http-common/src/index.ts:114:17)
at /Users/xxxx/Downloads/grand-stack-starter-master/api/node_modules/apollo-link-http-common/src/index.ts:145:11
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
name: 'ServerError',
response:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: [Object],
[Symbol(Response internals)]: [Object] },
statusCode: 400,
result: { errors: [Array] } },
message: 'Network error: Response not successful: Received status code 400',
extraInfo: undefined }
I started with multiple complex codes and this is pretty much the most stripped down version. When I run the seedDB command after the seed-mutation.js file was modified to:
export default /* GraphQL */ `
mutation {
p1: CreatePatient(
id: "p1",
name: "John Doe 1"
) {
id
name
}
r1: CreateReview(id: "r1", stars: 4, text: "Great IPA selection!", date: { formatted: "2016-01-03"}) {
id
}
}
`;
the database gets populated, however the two nodes are not connected to each other, as expected (basically, this is the code with the AddUserReviews removed). How do I build the relation between the nodes through using graphql and seedDb? What am I missing?
You can use GraphQL Playground to inspect the GraphQL API (in the "Docs" tab):
to ensure the mutations you are calling have the correct name and arguments. From inspecting the schema, it looks like instead of AddUserReviews, you want AddPatientReviews?

Cannot invoke function with an argument list of type in Swift Test class

I am attempting to write a test as shown below, but I receive the following compiler error => Cannot invoke 'include' with an argument list of type '([User], userId: String)'.
func testInclude() {
var users = mockUsers()
XCTAssert(self.viewController.include(users, userId: "2"), "Pass")
}
The mockUsers function is as shown below.
func mockUsers() -> [User]{
var users = [User(userId: "1", username: "soupguy", gender: 0, name: "Bob"),
User(userId: "2", username: "breadeater", gender: 1, name: "Alice"),
User(userId: "3", username: "lawnmowersrule", gender: 0, name: "Alex")]
return users
}
The include function that is being tested is shown below.
public func include(array: [User], userId: String) -> Bool {
for item in array {
if item.userId == userId {
return true
}
}
return false
}
I have tried changing types and storing the results in temporary variables, but have had no success in getting the test to compile.
My best guess is that one of your 'func' are wrong, go back and check all of you functions and cleaning your project form product tab on the Xcode menu bar might help as well.

Resources