I have an NestJS API in front of an InfluxDB. In the API I want to add property description via the ApiProptery decorator from nestjs/swagger.
My Problem here is that I don't know how to create a proper description for a map.
Here is my model:
import { Precision } from '../shared/enums';
import { IsEnum, IsInt, IsOptional } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '#nestjs/swagger';
import { IsPrimitive } from '../shared/decorator/decorators';
export class CreateMeasurementDto {
#IsOptional()
#IsInt()
#ApiPropertyOptional()
timestamp: number;
#IsOptional()
#IsEnum(Precision)
#ApiPropertyOptional({ enum: Precision })
precision: Precision;
#ApiProperty({
description:
'Key/value pairs; values can be of type string, boolean or number.',
type: Map,
})
#IsPrimitive()
datapoints: Map<string, string | boolean | number>;
}
What I get in the SwaggerUi schema section is this:
CreateMeasurementDto{
timestamp number
precision string
Enum:[ s, ms, u, ns ]
datapoints* Map {
}
}
I want at least give an example or describe an element of the map. Both would be awesome.
The map is allowed to have strings as keys, while values can be string, boolean or number.
Here is a possible payload, that would be accepted:
{
"precision": "s",
"datapoints": {
"voltage": 123.6456,
"current": 123
}
}
With the latest version of nestjs/swagger which is version 4, you can define Raw Definitions Swagger Documentations
#ApiProperty({
type: 'object',
additionalProperties: {
oneOf: [
{ type: 'string' },
{ type: 'number' },
{ type: 'boolean' }
]
}
})
datapoints: Map<string, string | boolean | number>;
Related
import { GraphQLString, GraphQLScalarType } from 'graphql'
import { city } from '../../Entities/Cities'
export const CREATE_CITY = {
type: Citytype,
args: {
Name: { type: GraphQLString },
CountryCode: { type: GraphQLString },
District: { type: GraphQLString },
Info: { type: GraphQLString }
},
resolve(parent: any, args: any) {
const { Name, CountryCode, District, Info } = args;
city.insert({ Name, CountryCode, District, Info });
return args;
},
}`
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
#Entity()
export class city extends BaseEntity{
#PrimaryGeneratedColumn()
Id!: number;
#Column({ type: "char", length: 35 })
Name!: string;
#Column({ type: "char", length: 3 })
CountryCode!: string;
#Column({ type: "char", length: 20 })
District!: string;
#Column({ type: "string" })
Info!: string;
}
<I'm trying to learn graphql and I'm a day in>
The Info type is suppose to be a json, in my database it looks like {"Population": 127800} with the same definition. I'm fully aware that it isn't a string/GraphQLString but I don't know how to obtain the value of this object. It returns Info: null and an error - "message": "String cannot represent value: { Population: 127800 }" for obvious reasons.
The code has the same structure as the tutorial I watched and only this video.
Link: https://www.youtube.com/watch?v=fov5e6XJgwc&ab_channel=PedroTech
Q: I want to know how to get the population ex. {"Population": 127800} when I query
it should look like Info: {"Population": 127800}
Optional: How to get the value of population if it looks like - Info: 127800
I'm trying to separate my params from my JSX in the react-particles-js library.
I place my params in an Object:
let options = {
"particles": {
"number": {
"value": 50
},
"size": {
"value": 3
}
},
"interactivity": {
"events": {
"onhover": {
"enable": true,
"mode": "repulse"
}
}
}
}
Then I write my JSX:
<Particles params={options}/>
When I do so I get the error
The types of 'interactivity.events.onhover.mode' are incompatible between these types.
Type 'string' is not assignable to type '"repulse" | "grab" | "push" | "remove" | "bubble" | InteractivityMode[] | undefined'. TS2322
I can't import the InteractivityMode interface since it's not exported in the library. I'm not sure what to do here.
If you check the type definition of it
https://github.com/Wufe/react-particles-js/blob/master/index.d.ts
export type IParticlesParams = RecursivePartial<{
...
}>
export interface ParticlesProps {
width?: string;
height?: string;
params?: IParticlesParams;
style?: any;
className?: string;
canvasClassName?: string;
}
type Particles = ComponentClass<ParticlesProps>;
So import the type IParticlesParams and use it
import { Particles, IParticlesParams } from "react-particles-js";
let options: IParticlesParams = {
...
}
And if there are any further type error, handle it inside your file as normal would be fine
I'm trying to build a Azure cognitive text translator app in angular. Initially I need to load the supported languages. But when I use this link https://api.cognitive.microsofttranslator.com/languages?api-version=3.0. I'm getting response like this
"translation": {
"af": {
"name": "Afrikaans",
"nativeName": "Afrikaans",
"dir": "ltr"
},
"ar": {
"name": "Arabic",
"nativeName": "العربية",
"dir": "rtl"
},
"bg": {
"name": "Bulgarian",
"nativeName": "Български",
"dir": "ltr"
},
...
}
How to create a model that holds this type of json?
When I tried json2ts.com for building the model, it creates object for each language like
export interface Af {
name: string;
nativeName: string;
dir: string;
}
export interface Ar {
name: string;
nativeName: string;
dir: string;
}
export interface Bg {
name: string;
nativeName: string;
dir: string;
}
export interface Translation {
af: Af;
ar: Ar;
bg: Bg;
}
Do I need to create interface for all the available languages?
are there any other simple way to handle this?
The translation property of that object is a key-value map.
You could model the whole thing as follows:
type Dir = "ltr" | "rtl";
interface Translation {
name:string;
nativeName:string;
dir: Dir;
}
interface LangResponse {
translation: {[langCode:string]: Translation};
}
You could define a Typescript interface modeling the JSON data.
export interface LanguageInfo {
name: string
nativeName: string
dir: string
code?: string
toScripts?: Array<LanguageInfo>
}
export interface TranslationLanguages {
langCode: string
info: LanguageInfo
}
function fromJSON(json_data: string | Object): TranslationLanguages {
let obj: TranslationLanguages;
if (typeof json_data === "object") {
obj = json_data as TranslationLanguages;
} else {
obj = JSON.parse(json_data);
}
return obj;
}
I have a class which has multiple interfaces inside of it to model a JSON data. For example:
interface A {
id: number;
}
interface B {
name: string;
surname?: string;
}
class MyClass implements A {
people: B[];
notes: string[];
function1(){...}
function2(){...}
}
And I have a JSON in the same structure:
{
id: 1,
people: [
{
name: "john"
},
{
name: "alice",
surname: "smith"
}
],
notes: [ "Very important top secret note" ]
}
Can I create an instance of MyClass from this JSON directly?
Your data structure is almost the same as your class, you'd have to add an id property to the class
class MyClass implements A {
id: number;
// ....
}
The problem is if you were trying to do something like this:
let data: MyClass = {
id: 1,
people: [
{
name: "john"
},
{
name: "alice",
surname: "smith"
}
],
notes: [ "Very important top secret note" ]
}
This won't work because your json does not have the methods (function1, function2).
One solution would be to really instantiate the MyClass and pass the json, or have a constructor method for that like
class MyClass {
static createFrom(jsonData: A & B): MyClass {
// create the objct and return
}
}
Or, you could create a variable of that type by combining an existing instance of the class and spreading the json.
Like so:
let json = {
id: 1,
people: [
{
name: "john"
},
{
name: "alice",
surname: "smith"
}
],
notes: ["Very important top secret note"]
}
const c = new MyClass();
let mClass: MyClass = {...json, function1: c.function1, function2: c.function2 };
mClass.function1();
Link to playground
I am using the latest 2.0-preview version of Polymer. I'd like to set default properties, and the Polymer documentation describes how to do it in Polymer 1.x. I was unable to find any changes in this approach for v2.0. But it seems to only work for primitive properties and not objects:
"use strict";
class NewElement extends Polymer.Element {
static get is() {
return 'new-element';
}
static get config() {
return {
properties: {
user: {
// type: Object, <-- doesn't help anyway
firstName: {
type: String,
value: "John",
// observer: '_callObserver' <-- FYI observers don't work properly too if this usage...
},
lastName: {
type: String,
value: "Doe"
}
},
position: {
type: String,
value: "Waiter" // <-- will set a high-level default value properly correctly
}
},
// observers: [
// '_callObserver(user.*)' <-- ...but works using this approach
// ]
}
}
constructor() {
super();
console.dir(this); // <-- see screenshots below
// this.user = { firstName: "John", lastName: "Doe" }; <-- works if initialized manually
}
}
customElements.define(NewElement.is, NewElement);
As you can see here there is a getter, and when I click on it, I see that user field is undefined.
What am I doing wrong?
It looks like you're trying to nest property declarations, which is not supported. You can declare an object property that contains subproperties (not property declarations that have type, observer, etc.).
The user property declaration:
properties: {
user: {
type: Object,
firstName: {
type: String,
value: "John",
},
lastName: {
type: String,
value: "Doe"
}
},
},
should actually look like this:
properties: {
user: {
type: Object,
value: function() {
return {
firstName: "John",
lastName: "Doe"
};
}
},
},
codepen