1

I am a newbie in TypeScript

const conversations = await Conversation
                .query()
                .whereRaw("FIND_IN_SET(" + user_id + ", participants)")
                .orderBy("last_message_timestamp", "desc")
                .limit(10)
                .offset(a)
    
    var conversations_array: any = [];
    
    for (var i = 0; i < conversations.length; i++) {
    conversations_array.push(conversations[i]);
    }
    
    for (var i = 0; i < conversations.length; i++) {
    conversations_array[i].last_message = "Test";
    }
    
    return conversations_array

It gets data from Lucid (Adonis JS Database ORM) and pushes those to an array called conversations_array.

Then I add another key to that array of objects called "last_message"

Problem is that When I return that conversations_array from API I can only see database fields and I don't see that "last_message" key. How can I return the whole of conversations_array including "last_message"?

For example I can see this

return conversations_array[0].last_message
Utku Dalmaz
  • 9,780
  • 28
  • 90
  • 130

1 Answers1

0

Your Conversation model should have a last_message property, like (if you're using Typescript):

@column()
public lastMessage: number;

If you don't want to persist this property (or this prop does not exists in database table), you can fill your model object based in the columns selected:

In your model:

public static get columns() {
    return [
        ...
        all previous columns without lastMessage (comma separated)
        ...
    ]
}

I personally built a function to fill it based on my columns array:

export function getFieldsToUpdate(requestFields: any, fieldNames: string[]) {
  let fieldsToUpdate = {};

  fieldNames.forEach((fieldName) => {
    if (fieldName in requestFields)
      fieldsToUpdate[fieldName] = requestFields[fieldName];
  });
  return fieldsToUpdate;
}

Then in the controller I would use:

conversation.fill(getFieldsToUpdate(request.all(), Conversation.columns));

This way I can fill the object without the last_message property

tomrlh
  • 1,006
  • 1
  • 18
  • 39