swagger-codegen icon indicating copy to clipboard operation
swagger-codegen copied to clipboard

[ObjC] Wrong generation of additionalProperties

Open cbornet opened this issue 10 years ago • 27 comments

The following definition

{
  "swagger": "2.0",
  "info": {
    "version": "1.0.0",
    "title": "Swagger Petstore"
  },
  "paths": {
    "/pets": {
      "get": {
        "description": "Returns all pets from the system that the user has access to",
        "produces": [
          "application/json"
        ],
        "responses": {
          "200": {
            "description": "A list of pets.",
            "schema": {
              "type": "array",
              "items": {
                "$ref": "#/definitions/Pet"
              }
            }
          }
        }
      }
    }
  },
  "definitions": {
    "PetMap": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/Pet"
      }
    },
    "Pet": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer",
          "format": "int64"
        }
      }
    }
  }
}

Generates SWGPetMap.h

@interface SWGPetMap : NSMutableDictionary

and SWGPetMap.m

#import "SWGPetMap.h"

@implementation SWGPetMap

- (instancetype)init {
  self = [super init];

  if (self) {
    // initalise property's default value, if any

  }

  return self;
}

/**
 * Maps json key to property name.
 * This method is used by `JSONModel`.
 */
+ (JSONKeyMapper *)keyMapper
{
  return [[JSONKeyMapper alloc] initWithDictionary:@{  }];
}

/**
 * Indicates whether the property with the given name is optional.
 * If `propertyName` is optional, then return `YES`, otherwise return `NO`.
 * This method is used by `JSONModel`.
 */
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
  NSArray *optionalProperties = @[];

  if ([optionalProperties containsObject:propertyName]) {
    return YES;
  }
  else {
    return NO;
  }
}

/**
 * Gets the string presentation of the object.
 * This method will be called when logging model object using `NSLog`.
 */
- (NSString *)description {
    return [[self toDictionary] description];
}

@end

which fails to compile because toDictionary is not declared for NSMutableDictionary (it's a JSONModel method)

cbornet avatar Feb 22 '16 11:02 cbornet

The above was generated with 2.1.5. Also I think #1540 might not be fixed.

cbornet avatar Feb 22 '16 11:02 cbornet

@cbornet If I understand correctly, PetMap should not be generated as a separate model as it's simply a map, right ?

wing328 avatar Feb 22 '16 14:02 wing328

Right now I don't know how it should be handled. I will have a look. Maybe @samskiter knows better ?

cbornet avatar Feb 22 '16 15:02 cbornet

According to json schema, when additionalProperties is assigned to a schema like this, the intention is that every value of an object's key-value pair must validate against that schema (if they are not already validated via properties or patternProperties).

I generally try to avoid dynamic keys like this and instead just opt for a plain array. Writing classes using things like JSONModel is basically impossible with dynamic keys.

However, there is a way to represent this schema in objective-c now that there is support(ish) for generics:

@property NSDictionary<NSString *, SWGPet *>* petmap;

I.e. a map from strings to pets. I'm not sure whether petmap should be generated as a separate class or not, if it were generated as a separate class I might go for:

@interface SWGPetMap : NSMutableDictionary<NSString *, SWGPet *>
@end

But I'm not even sure if that's valid syntax! (you could do it in Java)

Hope that helps?

samskiter avatar Feb 22 '16 15:02 samskiter

worth thinking about, how do you represent this?

"definitions": {
    "PetMap": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/Pet"
      },
      "myname": "string",
      "otherThing": "number"
    },
    "Pet": {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer",
          "format": "int64"
        }
      }
    }
  }

maybe this? ("additionalProperties" should never collide right?)

@interface SWGPetMap : NSObject
@property NSDictionary<NSString *, SWGPet *>* additionalProperties;
@property NSNumber* otherThing;
@property NSString* myname;
@end

samskiter avatar Feb 22 '16 15:02 samskiter

See this. It seems JSONModel has some support for dynamic keys.

cbornet avatar Feb 22 '16 16:02 cbornet

Ah ok, hadn't seen that. We have a similar library to JSONModel that we use internally that doesn't support this.

I'm curious what use it has (other than performance) over an array? Every instance I've seen, it would probably be better to use an array. (EDIT: I suppose for many-to-many relationships, you might use unique ID's in the keys. But it's still a performance improvement rather than anything else...)

For ref: JSONSchema2Pojo does as I've suggested above - it has an additionalProperties field. See: https://github.com/joelittlejohn/jsonschema2pojo/wiki/Reference

samskiter avatar Feb 22 '16 16:02 samskiter

You mean : "what's the point of using a json map over a json array ?". Well, I'm not sure : probably performance as you say and uniqueness of keys. But I want to document an external API with swagger that uses maps so I don't really have a choice...

cbornet avatar Feb 22 '16 16:02 cbornet

So it seems to me that SWGMap should be generated as

@interface SWGPetMap : NSMutableDictionary<Pet>

and not have the implementation.

cbornet avatar Feb 22 '16 17:02 cbornet

(Can you do definitely do that?)

On reflection I think JSONSchema2Pojo do it right, i.e:

@interface SWGPetMap : NSObject
@property NSDictionary<NSString *, SWGPet *>* additionalProperties;
@end

samskiter avatar Feb 22 '16 17:02 samskiter

With Java, we don't do as JSONSchema2Pojo, models that have additionalProperties are mapped to java.util.Map. For instance the spec above generates

public class PetMap extends HashMap<String, Pet>

cbornet avatar Feb 22 '16 18:02 cbornet

Fair enough. I'm not sure if

@interface SWGPetMap : NSMutableDictionary<Pet>

is valid syntax....

samskiter avatar Feb 22 '16 18:02 samskiter

Yes you're probably right about the syntax. I got it from the JSONModel issue but it feels wrong.

cbornet avatar Feb 22 '16 20:02 cbornet

Actually the syntax is not a generic but a special JSONModel protocol so the syntax really is NSMutableDictionary<Pet>. But I'm not sure JSONModel supports some kind of "inline" model. I don't see anything like that in the examples.

cbornet avatar Feb 22 '16 21:02 cbornet

From this SOF I get that only classes that extend JSONModel can be mapped. Note that this issue also occurs with arrays.

    "PetList": {
      "type": "array",
      "items": {
        "$ref": "#/definitions/Pet"
      }
    }

gets generated as

@interface SWGPetList : NSMutableArray

which is wrong with JSONModel. @wing328 do you have any idea for this kind of mappers that only support mapping on class properties ?

cbornet avatar Feb 22 '16 22:02 cbornet

@wing328 to answer your initial question: yes, if we could use NSDictionary<NSString *, SWGPet *> everywhere instead of SWGPetMap and not generate SWGPetMap at all, I guess we could solve this issue. Is there something like that in the generator ? Same thing with NSArray<SWGPet *> and SWGPetList

cbornet avatar Feb 22 '16 23:02 cbornet

Sorry, to clarify re: syntax. I wasn't sure whether you could narrow generics through subclassing like that in Objective-C.

Yes re: JSONModel. you must subclass JSONModel for it to provide reflective access to your data. My 2 cents would still go to creating an 'additionalProperites' field as that is most flexible and easiest to implement but I understand for consistency, subclassing NSDictionary might be better. So I'll step out now :)

samskiter avatar Feb 23 '16 00:02 samskiter

So I have a solution using custom property setters but this requires to generate code that is different if the property is a PetMap, a dictionary of PetMap, an array of PetMap, ... or another type. Example for a Response definition:

    "Response": {
      "type": "object",
      "properties": {
        "petmap": {
          "$ref": "#/definitions/PetMap"
        }
      }
    },

The following method in Response.m

- (void)setPetmapWithNSDictionary:(NSDictionary*)dict
{
  self.petmap = [Pet dictionaryOfModelsFromDictionary:dict error:nil];
}

Will make the mapping work.

If the petmaps attribute is a NSDictionary of PetMap, the needed code would be:

- (void)setPetmapsWithNSDictionary:(NSDictionary*)dict
{
  NSMutableDictionary *mutableDict = [NSMutableDictionary new];
  for (NSString *key in dict.allKeys)
    mutableDict[key] = [Pet dictionaryOfModelsFromDictionary:dict[key] error:nil];
  self.petmaps = mutableDict;
}

So the question is : how to generate the correct code depending on the attribute type ? @wing328 ?

cbornet avatar Feb 23 '16 18:02 cbornet

@cbornet I just submitted https://github.com/swagger-api/swagger-codegen/pull/2226 for add more boolean flags to CodegenProperty.

Would that help?

wing328 avatar Feb 24 '16 02:02 wing328

Yes, that will surely help ! The issue I see is that I would need to not only know the type of the attribute (eg. petmapmap is a map of PetMap) but also the type of the model itself (ie. PetMap itself is a map of Pet). I will investigate if I can find a solution here.

cbornet avatar Feb 24 '16 09:02 cbornet