Skip to content

Commit

Permalink
Merge pull request #10 from fussybeaver/ND-include-parameter
Browse files Browse the repository at this point in the history
User example and include parameter support
  • Loading branch information
fussybeaver committed Oct 22, 2022
2 parents 1ade8a8 + 03982d6 commit c20cf53
Show file tree
Hide file tree
Showing 9 changed files with 272 additions and 146 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ src/endpoints/*_swagger.rs
/*.json
/templates/api.mustache
/Cargo.lock
/pagerduty-models-codegen.iml
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "praiya"
description = "An async PagerDuty API client"
license = "Apache-2.0"
version = "0.2.1"
version = "0.3.0"
authors = ["Praiya contributors"]
homepage = "https://github.com/fussybeaver/praiya"
repository = "https://github.com/fussybeaver/praiya"
Expand Down
8 changes: 3 additions & 5 deletions examples/switch_incident_slack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ use std::collections::HashSet;

use futures_util::TryStreamExt;
use praiya::{
api::incidents::ListIncidentsParamsBuilder,
default_models::{Incident, ServiceReference},
slack_models::SlackConnection,
ParamsBuilder, Praiya,
api::incidents::ListIncidentsParamsBuilder, default_models::Incident, models::Service,
slack_models::SlackConnection, ParamsBuilder, Praiya,
};

// Replace with appropriate values...
Expand Down Expand Up @@ -41,7 +39,7 @@ async fn main() -> Result<(), praiya::errors::Error> {

let mut services = HashSet::new();
for incident in &incidents {
if let Some(ServiceReference { id: Some(id), .. }) = &incident.service {
if let Some(Service { id: Some(id), .. }) = &incident.service {
services.insert(String::clone(id));
}
}
Expand Down
82 changes: 82 additions & 0 deletions examples/validate_users.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//! This example will fetch all users and check their notification rules

use futures_util::TryStreamExt;
use praiya::Praiya;

use praiya::api::users::ListUsersParamsBuilder;
use praiya::models::{ContactMethod, ContactMethodTypeEnum, NotificationRule, User, UserRoleEnum};
use praiya::ParamsBuilder;

// Replace with appropriate values...
const PAGERDUTY_TOKEN: &str = "";

#[tokio::main]
async fn main() -> Result<(), praiya::errors::Error> {
let pagerduty = Praiya::new(PAGERDUTY_TOKEN);

let params = {
let mut option = ListUsersParamsBuilder::new();
let include = vec!["notification_rules"];

option.include(include);
option.build()
};

let users: Vec<User> = pagerduty
.users()
.list_users(params)
.try_collect()
.await
.expect("failed to fetch users");

let default_contact_types = vec![
ContactMethodTypeEnum::EMAIL_CONTACT_METHOD,
ContactMethodTypeEnum::SMS_CONTACT_METHOD,
ContactMethodTypeEnum::PHONE_CONTACT_METHOD,
];

for user in &users {
match user {
User {
role: Some(role),
notification_rules: Some(rules),
summary: Some(summary),
..
} if !vec![
UserRoleEnum::READ_ONLY_USER,
UserRoleEnum::READ_ONLY_LIMITED_USER,
]
.iter()
.any(|r| r == role)
&& default_contact_types.iter().all(|c| {
rules.iter().any(|r| match r {
NotificationRule {
contact_method: Some(ContactMethod { _type, .. }),
..
} if c == _type => true,
_ => false,
})
}) =>
{
println!("User is valid: {}", &summary);
}
User {
summary: Some(summary),
role: Some(role),
notification_rules: Some(notification_rules),
..
} => println!(
"User is not a responder, or missing notification rules: {:?}, {:?}, {:?}",
summary,
role,
notification_rules
.iter()
.map(|n| n.contact_method.as_ref().unwrap()._type.as_ref())
.collect::<Vec<&str>>()
),
_ => println!("Failed to parse user {:?}", user),
}
}

Ok(())
}
47 changes: 41 additions & 6 deletions java/pagerduty/PagerDutyCodegen.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,15 @@ public void processOpts() {
}
}

private static final HashMap<String, Object> patchOperationBodyNames = new HashMap();
private static final Map<String, Object> patchOperationBodyNames = new HashMap();
private static final Map<String, List<String>> referenceOverrideExceptions = new HashMap();
static {
referenceOverrideExceptions.put("Incident", Arrays.asList("LogEntry"));
referenceOverrideExceptions.put("Team", Arrays.asList("Team"));
referenceOverrideExceptions.put("ResolveReason", Arrays.asList("Incident"));
// Note: this is really MergeIncidents
referenceOverrideExceptions.put("IdMergeBody", Arrays.asList("Incident"));
}

@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
Expand Down Expand Up @@ -164,7 +172,7 @@ public CodegenModel fromModel(String name, Schema schema, Map<String, Schema> al

if (allDefinitions != null) {
refSchema = allDefinitions.get(ref);
if (refSchema instanceof ComposedSchema) {
if (refSchema instanceof ComposedSchema) {
final ComposedSchema refComposed = (ComposedSchema) refSchema;
final List<Schema> allOf = refComposed.getAllOf();
if (allOf != null && !allOf.isEmpty()) {
Expand Down Expand Up @@ -344,7 +352,7 @@ public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
String modelName = toModelName(entry.getKey());
Map<String, Object> inner = (Map<String, Object>) entry.getValue();
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");

for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model");
allModels.put(cm.classname, cm);
Expand Down Expand Up @@ -470,7 +478,7 @@ public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
// Sanitise some datatypes, remove the composed prefix and
// inline response from property datatypes, since we generate
// these now with better names.

if (prop.datatype.startsWith("AllOf")) {
if (!allModels.keySet().contains(prop.datatype) || allModels.get(prop.datatype).vars.isEmpty()) {
prop.datatype = prop.datatype.replace("AllOf", "");
Expand All @@ -485,6 +493,32 @@ public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
prop.getItems().datatype = prop.getItems().datatype.replaceFirst("^InlineResponse[0-9]*", "");
}

// Don't use Reference types, if possible, just point to the full model.
// This ensures that we can use 'include' parameters in API endpoints.
// We make sure required fields are marked optional on the full model to ensure we can deserialize.

if (prop.datatype.endsWith("Reference")) {
String fullMdlName = prop.datatype.replaceFirst("Reference$", "");

if (allModels.keySet().contains(fullMdlName)) {
if (!referenceOverrideExceptions.keySet().contains(model.classname)
|| !referenceOverrideExceptions.get(model.classname).contains(fullMdlName)) {
prop.datatype = fullMdlName;
}
}
}

if (prop.getItems() != null && prop.getItems().datatype.endsWith("Reference")) {
String fullMdlName = prop.getItems().datatype.replaceFirst("Reference$", "");

if (allModels.keySet().contains(fullMdlName)) {
if (!referenceOverrideExceptions.keySet().contains(model.classname)
|| !referenceOverrideExceptions.get(model.classname).contains(fullMdlName)) {
prop.getItems().datatype = fullMdlName;
}
}
}

if (prop.datatype != null && prop.datatype.equals("String") && prop.allowableValues == null) {
prop.vendorExtensions.put("x-rustgen-is-string", true);
model.vendorExtensions.put("x-rustgen-has-string", true);
Expand Down Expand Up @@ -555,7 +589,7 @@ public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
// required fields, or we will crash on deserialization.
for (CodegenProperty prop : model.requiredVars) {
// chrono does not implement Default
if (prop.datatype != null && !(prop.datatype.startsWith("chrono"))) {
if (prop.datatype != null && !(prop.datatype.startsWith("chrono")) && !allModels.containsKey(model.classname + "Reference")) {
prop.vendorExtensions.put("x-rustgen-is-required", true);
}
}
Expand Down Expand Up @@ -612,6 +646,7 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
}
return objs;
}

@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
Expand All @@ -623,7 +658,7 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert

@Override
public CodegenParameter fromRequestBody(RequestBody body, String name, Schema schema, Map<String, Schema> schemas,
Set<String> imports) {
Set<String> imports) {
CodegenParameter param = super.fromRequestBody(body, name, schema, schemas, imports);

// patches the Body* Models with better names
Expand Down
Loading

0 comments on commit c20cf53

Please sign in to comment.