Grais Rest: get a Json object from a "lastName" and not "id" - rest

How get a user of this class, from a lastName, not from the id.
in my example i use a REST web service.
My class USER.groovy in Grails:
class User {
String firstName
String lastName
String zipcode }
class UrlMappings.groovy
class UrlMappings {
static mappings = {
/user/$id" (controller: "user") {
action = [GET: "show"]
}
}
}
def show in UserController.groovy
def show = {
User user = User.get(params.id)
if (user) {
render user as JSON
} else {
SendNotFoundResponse()
}
}

As I understand, your problem that you don't know how to query domain by other fields that id. For current example you can use:
User.findByFirstName(params.id)
And, please read about GORM querying - http://grails.org/doc/latest/guide/GORM.html#querying

Related

Apollo GraphQL returns an empty field

I want to query all the products no user has viewed.
The structure is
model Products {
id string
views Views[]
}
model Views {
id string
createdAt DateTime
user User
}
model User {
id string
email string
}
I want to get all the products that no one has viewed. The following query is not working, but I think it should be similar (if this is possible)
query {
Products(where: { views: { is: empty }}) {
id
views
}
}

Unknown argument error when creating record

I'm encountering some interesting behaviour when using Prisma ORM. It is related to Prisma's generated types, and I've been skimming the docs trying to find out more, but there doesn't seem to be much info about generated types in there (please correct me if I'm mistaken). Here's the behaviour:
Say I have a model with two 1-1 relations (Profile in the example below):
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int #id #default(autoincrement())
name String
profile Profile?
}
model Profile {
id Int #id #default(autoincrement())
name String
userId Int?
user User? #relation(fields: [userId], references: [id])
photoId Int?
photo Photo? #relation(fields: [photoId], references: [id])
}
model Photo {
id Int #id #default(autoincrement())
url String
profile Profile?
}
The following code works when creating a new profile:
const user = await prisma.user.create({ data: { name: "TestUser" } });
const profile = await prisma.profile.create({
data: {
name: "TestProfile",
user: { connect: { id: user.id } },
photo: { create: { url: "http://example.com/img" } },
},
});
... but this fails with an error:
const user = await prisma.user.create({ data: { name: "TestUser" } });
const profile = await prisma.profile.create({
data: {
name: "TestProfile",
userId: user.id,
photo: { create: { url: "http://example.com/img" } },
},
});
The error is:
Unknown arg userId in data.userId for type ProfileCreateInput. Did you mean user? Available args:
type ProfileCreateInput {
  name: String
  user?: UserCreateNestedOneWithoutProfileInput
  photo?: PhotoCreateNestedOneWithoutProfileInput
}
Why is the second create-profile code invalid?
Prisma essentially generates two type definitions for a create query. This is implemented with a XOR type, which ensures that only one definition out of two is fully specified and passed to the query:
export type ProfileCreateArgs = {
/* ... */
data: XOR<ProfileCreateInput, ProfileUncheckedCreateInput>;
}
The definitions are called checked and unchecked, the former using nested fields and the latter using raw ids:
export type ProfileCreateInput = {
id?: number;
/* ... */
user?: UserCreateNestedOneWithoutProfileInput;
photo?: PhotoCreateNestedOneWithoutProfileInput;
}
export type ProfileUncheckedCreateInput = {
id?: number;
/* ... */
userId?: number;
photoId?: number;
}
Which basically means that you either provide all references as connect, create etc. relations (checked) or as raw ids (unchecked). You cannot mix the styles, this is not supported.

angular 2 how to add a model within model

I am getting a response json from API like below.
student: {
name : abc,
address : {
city : ca,
state:abc
},
age : 10
}
In order to bind this to a model, i need a model similar to this
class student {
name:string;
age:number;
address:{
city:string;
state:string
}
}
But when I bind the data to the above model. Address data is not binding to model.
Please suggest the right way to write a model to bind the above data.
export class A {
name:string;
age:number;
address:Adress;
}
export class Adress
city:string;
state:string
}
You need to instantiate an instance of the Student class, i.e.
class Student {
// Define Student properties here
name:string;
age:number;
// ...
constructor(options) {
// Set Student properties here
this.name = options.name;
this.age = options.age;
this.address = options.address;
// ...
}
}
// Then:
const student = new Student(jsonData);

How to exclude property of a collection in JSON rendering in Grails 2.3

I am trying to setup a rest webservice (JSON) this is what I am getting:
{"name":"test","routines":[{"class":"Routine","id":1},{"class":"Routine","id":2}]}
This is what I want to get:
{"name":"test","routines":[{"name": "routine-1"},{"name": "routine-2"}]}
I have these domains:
class Program {
String name;
static hasMany = [routines: Routine]
}
class Routine {
String name
}
I have this controller:
class ProgramController extends RestfulController {
static responseFormats = ['json']
def show(Program program) {
respond program
}
}
I added this in the resources.groovy
programRenderer(JsonRenderer, Program) {
excludes = ['class', 'id']
}
routineRenderer(JsonRenderer, Routine) {
excludes = ['class', 'id']
}
How do I include the name property of Routine in the json response using the show method/action of ProgramController?
The ObjectMarshaller approach is the technically correct way. However, the code is cumbersome to write and it's a maintenance headache syncing the fields of the domain with the marshaller.
In the spirit of being Groovy and keeping things really simple, we've been quite happy just adding a little out() method to each REST domain.
Program.groovy
class Program {
String name
static hasMany = [routines: Routine]
def out() {
return [
name: name,
count: routines?.size(),
routines: routines?.collect { [name: it.name] }
]
}
}
ProgramController.groovy
import grails.converters.JSON
class ProgramController {
def show() {
def resource = Program.read(params.id)
render resource.out() as JSON
}
}
JSON Response
{
name: "test",
count: 2,
routines: [{ name: "routine-1" }, { name: "routine-2" }]
}
The out() method approach makes it easy to customize the response JSON, such as adding count for the number of routines.

How to obtain JSON (or XML) response from Grails?

I have 1 domain class, 1 controller, 1 URL mapping (see below). I want to send request, and receive JSON response.
But currently my request is correctly mapped to the correspondent controller method, the method is successfully executed, and then I get an error with message that jsp-file not available.
How to explain Grails, that I don't need no jsp-files: I want to receive/parse JSON requests, and send JSON responses right from my controllers?
class Brand {
String name
String description
String logoImageURL
static constraints = {
name(blank: false)
}
}
---------------------------
class UrlMappings {
static mappings = {
"/brands"(controller: "brand", parseRequest: true, action: "list")
}
}
---------------------------
import grails.converters.JSON
class BrandController {
def list = {
return Brand.list() as JSON
}
def show = {
return Brand.get(params.id) as JSON
}
def save = {
def brand = new Brand(name: params.name, description: params.description, logoImageURL: params.logoURL)
if (brand.save()) {
render brand as JSON
} else {
render brand.errors
}
}
}
============== Error message ===============
Request URL: http://localhost:8080/ShoesShop/brands
message /ShoesShop/WEB-INF/grails-app/views/brand/list.jsp
description The requested resource (/ShoesShop/WEB-INF/grails-app/views/brand/list.jsp) is not available.
It should work if you instead do:
def list = {
render Brand.list() as JSON
}