How to hide or exclude fields in strapi query? - strapi

I get all the properties in query, like even created_by,updated_by...
{
"client_ip": "Velit quo libero sun",
"verifier": "Voluptas ut sit sun",
"created_by": {
"id": 1,
"firstname": "admin",
"lastname": "admin",
"username": null
},
"updated_by": {
"id": 1,
"firstname": "admin",
"lastname": "admin",
"username": null
}}
Is there a way to remove these unwanted fields?

There are two thing you could do in the model and attributes validation
Use the private validation options on an attribute, to not return it in the default endpoints.
"attributes": {
"title": {
"type": "string",
"private": true
}
Check out the docs.
You can also disable the timestamps in your model, with:
{
"options": {
"timestamps": false
}
}
Check out the docs.
Something like the 2nd method, will soon be available for the created_by & updated_by attributes, it is a know issue since v3.1.x.

You can create a custom controller to reduce payload size or hide responses manually.
In your controller handler you can use the delete operator to remove unwanted props
Using optional chaining (?) (supported from Node.js version 14)
handlerName : async (ctx) => {
const results = await strapi.services?.["serviceName"]?.findOne() ?? {};
delete results?.created_by;
delete results?.updated_by;
ctx.send(results)
}

If you use strapi >= 4.0.0, you can provide privateAttributes to your model's options to exclude fields from both the admin panel and the response. https://docs.strapi.io/developer-docs/latest/development/backend-customization/models.html#model-options

if you dont want to show this attributes do this on model..
"options": {
"privateAttributes": [
"createdAt",
"updatedAt",
"publishedAt",
"createdBy",
"updatedBy"
]
and if you dont want to show your columns data Then do this.
await strapi.entityService.findMany('modelNAme', {
fields:['fieldName'] }.

Related

How to apply filters to extra fields from model serializer that are not in the model with django Rest

We have the SecurityEventItem that have the owner taken from another security_location model and returned.
The logic behind not having security_location direct as a foreign key is that we get events with security_location names that are not added yet to database, but we want them to be registered without adding the missing security location to the database.
class SecurityEventItemGetSerializer(serializers.ModelSerializer):
epc = RfidTagNestedSerializer()
owner = serializers.SerializerMethodField('get_owner')
def get_owner(self, member):
location = SecurityLocationSerializer(models.SecurityLocation.objects.get(name=member.security_location)).data
owner_name = ProductOwnerSerializer(models.ProductOwner.objects.get(id=location["owner"])).data
return owner_name["owner_name"]
class Meta:
model = models.SecurityEventItem
fields = ["id", "epc", "acknowledged", "firstSeenTimestamp", "security_location", "owner"]
The ViewSet bellow
class SecurityEventItemGetViewset(viewsets.ModelViewSet):
"""SecurityEventItemGet Viewset
API endpoint that allows security event items to be viewed.
Allowed actions:
"GET"
"""
queryset = models.SecurityEventItem.objects.all()
serializer_class = serializers.SecurityEventItemGetSerializer
http_method_names = ['get']
filter_backends = [DjangoFilterBackend]
search_fields = ["owner"]
filterset_fields = {
'acknowledged': ['exact'],
'epc': ['exact', "in"],
'security_location': ['exact', "in"],
'firstSeenTimestamp': ['gte', 'lte'],
}
I have tryed SearchFilter unsuccesfull as simillar to DjangoFilterBackend it does not recognize the owner field added that does not belong to the SecurityEventItem model.
The response is like this: and I would like to make a filter on the request passing a parameter "owner" added to the existing ones.
[
{
"id": 73,
"epc": {
"id": 8371,
"number": "1234",
"product": {
"id": 1,
"name": "default_product",
"ean": "",
"description": "default product for foreign/unknown RFID tags",
"category": {
"id": 1,
"name": "default_category",
"description": "default category for foreign/unknown RFID tags"
},
"info": []
},
"state": 1,
"info": [],
"owner": {
"id": 1,
"owner_id": 1,
"owner_name": "George"
}
},
"acknowledged": false,
"firstSeenTimestamp": "2022-02-21T09:44:08",
"security_location": "Test Location",
"owner": "Second Owner"
},
{
"id": 72,
"epc": {
"id": 105177,
"number": "303625D4580B2484000002CA",
"product": {
"id": 590,
"name": "A78R07",
"ean": "5940000792305",
"description": "Fata de perna 50x70",
"category": {
"id": 1,
"name": "default_category",
"description": "default category for foreign/unknown RFID tags"
},
"info": "{\"company\": \"HOTEL Nr1\"}"
},
"state": 1,
"info": [],
"owner": {
"id": 1,
"owner_id": 1,
"owner_name": "Regina"
}
},
"acknowledged": false,
"firstSeenTimestamp": "2022-02-21T09:31:16",
"security_location": "Front Desk",
"owner": "Second Company"
}
]
I would really appreciate if someone could teach me how to do that, there are plenty of information regarding model filtering, but no filters for the filters added to extra fields
SerializerMethodField is read-only.
This field is generated only at the time of serialization and does not exist in the database.
Filters work only with the database, but the owner field is not there.
I think you should annotate the queryset with the data you want (.annotate(owner=...), Subquery() ), then the filter can work because that field will be returned from the database.

Laravel Eloquen ORM can't return a model's relationship properly

I'm creating an API. In this repository there's a method called show() where a contact is returned. The user must provide an ID of a contact and can provide an array of relationships to be loaded and an array of the contact's attributes called fields.
return $this->contacts::with($request->relationships)->findOrFail($request->id, $request->fields);
But when $request->fields is provided all the relationships return null.
Request's Json:
{
"id": 75,
"fields": ["id", "name"],
"relationships": ["lead", "phone", "email", "address"]
}
Response's Json:
{
"id": 75,
"name": "Edgard Cesar Bertelli dos Reis",
"lead": null,
"phone": null,
"email": null,
"address": null
}
Any ideas of where I might be going wrong?
You must add the relations names in second parameters for findOrFail, in your example it could be like:
$fields = array_merge($request->relationships, $request->fields);
return $this->contacts::with($request->relationships)->findOrFail($request->id, $fields);

Google People API - Is it possible to get custom fields?

I need to import google contacts to my application. For that I try to use the Google People API but I didn't find an option to get the contacts custom fields.
Is it possible to get contact custom fields with the new Google People API?
Should I use the old Google Contacts API for that?
Thanks!
Request the userDefined projection with your personFields.
String url = "https://people.googleapis.com/v1/people/me/connections" +
"?personFields=names,emailAddresses,userDefined";
The response looks like this:
"userDefined": [
{
"metadata": {
"primary": true,
"source": {
"type": "CONTACT",
"id": "5629e24b082d1a66"
}
},
"key": "label1",
"value": "foo"
},
{
"metadata": {
"source": {
"type": "CONTACT",
"id": "5629e24b082d1a66"
}
},
"key": "label2",
"value": "bar"
}
]
For more details, see https://developers.google.com/people/api/rest/v1/people#Person.UserDefined
You can also update custom fields even though the documentation does not currently list userDefined as a valid field for updatePersonFields as the field mask.
https://developers.google.com/people/api/rest/v1/people/updateContact

Dojox/app keeping models synchronized with store

I am currently using dojox/app to create a SPA, and I am starting now to add stores and models. I have been able to create a store from a json object, to create a model from the store, and to bind fields to the model using dojox mvc. However, I have something that I have not yet been able to do: update a 2nd model that is binded to the same store as the 1st one.
I will give an example. I have this store:
win.global.modelApp = {};
modelApp.names = {
identifier: "id",
items: [{
"id": 1,
"First": "John",
"Last": "Doe",
},{
"id": 2,
"First": "John2",
"Last": "Doe",
}]
}
and then I create two models using this store in the config.json file:
"stores": {
"namesStore":{
"type": "dojo/store/Memory",
"params": {
"data": "modelApp.names"
}
}
},
"models": {
"namesXUnused": {
"modelLoader": "dojox/app/utils/mvcModel",
"type": "dojox/mvc/EditStoreRefListController",
"params":{
"store": {"$ref":"#stores.namesStore"}
}
},
"namesXUnused2": {
"modelLoader": "dojox/app/utils/mvcModel",
"type": "dojox/mvc/EditStoreRefListController",
"params":{
"store": {"$ref":"#stores.namesStore"}
}
}
}
Then, in my HTML file, I have a field binded to namesXUnused (property First), and another binded to namesXUnused2 (property First). When I edit the first field, I then have a button that commits these changes to the store. I can see via debugger that the store data has been correctly updated. However, I cannot get the second field to reflect the changes. Is there a way to refresh or recreate the model from the store?
Thank you,
I think you need to set "observable": true, on the store to use an Observable store since you want to have updates to the store be reflected back to the models. There are examples in the dojox/app/tests (and the dojox/mvc/tests) if you have problems, but just adding:
"observable": true, to your namesStore should do it.
"stores": {
"namesStore":{
"type": "dojo/store/Memory",
"observable": true,
"params": {
"data": "modelApp.names"
}
}
},
Regards,
Ed

CouchDB: Trouble querying a view with a key using rewrites

In CouchDB I have created a view called "zip", the map looks like this;
function (doc) {
if(doc.type == 'zip') {
emit(doc.zip_code, doc)
}
}
I then added a bunch of docs related to zip codes, a sample doc goes like this;
{
"_id": "zip/48114",
"_rev": "1-990b2c4f682ed0b6a27e2fa0c066c93d",
"zip_code": 48114,
"state": null,
"county": null,
"rep_code1": "INTL2",
"rep_code2": "MI1",
"type": "zip"
}
Now when I query the view directly like so,
http://localhost:5984/partslocator/_design/partslocator/_view/zip?key=48114
I get the row back that I am expecting;
{
"total_rows": 41683,
"offset": 20391,
"rows": [
{
"id": "zip/48114",
"key": 48114,
"value": {
"_id": "zip/48114",
"_rev": "1-990b2c4f682ed0b6a27e2fa0c066c93d",
"zip_code": 48114,
"state": null,
"county": null,
"rep_code1": "INTL2",
"rep_code2": "MI1",
"type": "zip"
}
}
]
}
I have then set up a vhost and am using rewrites, and my rewrite for 'zip' looks like this.
{from: "/zip/:zip", to: "_view/zip", query: {"key": ":zip"}}
To me this seems like it should be correct, however when I try to query the view with the rewrite url, it always returns zero rows.
rewrite url:
http://partslocatordev.com:5984/zip/48114
response:
{
"total_rows": 41683,
"offset": 41683,
"rows": []
}
Am I missing anything here?
Note: I am using rewrites in the same fashion with other views and they work, but I cannot figure out why this one in particular isn't.
It's likely that the rewriter is querying zip?key=":zip" rather than zip?key=:zip. You can use a formats field in your rewriter to name how different arguments should be typed. In this case, try this:
{
from: "/zip/:zip",
to: "_view/zip",
query: {"key": ":zip"},
formats: {
"zip": "int"
}
}
Alternatively, in your map function, emit a string as the ID rather than a number, like this:
function (doc) {
if(doc.type == 'zip') {
emit(String(doc.zip_code), doc)
}
}
That will handle cases where the zipcode isn't an integer, like in the UK.

Resources