Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
Updating Yaml File through Patch method not working

I have a Yaml file(layouts.yaml) of this format from which i want to perform crud Operations through REST Api:

Layouts:
        -
          Name: Default Layout
          LayoutId : 1
          ConfiguredSegments:
            LiveA :
                Height : 100
                Id : LiveA
            Ref1A :
                Height : 100
                Id : Ref1A
    

My controller Function to update a layout based on layout Id(I tried 2 ways which wont work):

1st way: //This does not seem to work

const raw = fs.readFileSync("layouts.yaml", 'utf8');
    const layoutData = YAML.load(raw);
    //function to update specific layout based on LayoutId
    export const updateSpecificLayout = (req, res)=>{
        const { id } = req.params;
        const { ConfiguredSegments } = req.body;
    
        const getLayoutList = JSON.parse(JSON.stringify(layoutData)); 
        
        getLayoutList.forEach(element => {if(element.LayoutId == id) element.ConfiguredSegments = 
        ConfiguredSegments 
            
        });
        let yaml = YAML.dump(getLayoutList);
         
          fs.writeFileSync("layouts.yaml", yaml, function (err,file){
             if(err) throw err;        
             console.log(`Layout with the id:${id} has been updated`);
      })      
    }
    

2nd way://This does not seem to work as well

    const raw = fs.readFileSync("layouts.yaml", 'utf8');
    const layoutData = YAML.load(raw);
    //function to update specific layout based on LayoutId
    export const updateSpecificLayout = (req, res)=>{
        const { id } = req.params;
        const { ConfiguredSegments } = req.body;
    
        const getLayout = JSON.parse(JSON.stringify(layoutData)); 
        const foundLayout = getLayout.Layouts.find((layout) => layout.LayoutId == id);
    
        if(ConfiguredSegments)foundLayout.ConfiguredSegments = ConfiguredSegments;
        console.log(`Layout with the id:${id} has been updated`);
    }

    

Through Postman i am testing my api with patch request with the following body:

    {
    "ConfiguredSegments": {
    "Ref2A": {
    "Height": 100,
    "Id": "LiveA"
    },
    "Ref3A": {
    "Height": 100,
    "Id": "Ref1A"
    }
    }
    }
    
 But the yaml file is not getting updated.Any other ways to achieve this ?
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can try using this method. Define a function which will be able to find and replace the object you are looking for. Your controller function:

export const updateSpecificLayout = (req, res)=>{
    const { id } = req.params;
    const { ConfiguredSegments } = req.body;

    const getLayoutList = JSON.parse(JSON.stringify(layoutData)); 

    const layoutToBeUpdated = getLayoutList.Layouts.find((layout) => layout.LayoutId == id );

    findAndReplace(getLayoutList.Layouts,layoutToBeUpdated.ConfiguredSegments,ConfiguredSegments)

      let yaml = YAML.dump(getLayoutList);
     
       fs.writeFileSync("layouts.yaml", yaml, function (err,file){
          if(err) throw err;        
          console.log(`Layout with the id:${id} has been updated`);
  })      
}

The helper function which can find and replace the data.

// Helper function to update layout data
function findAndReplace(object, value, replacevalue) {
    for (var x in object) {
      if (object.hasOwnProperty(x)) {
        if (typeof object[x] == 'object') {
          findAndReplace(object[x], value, replacevalue);
        }
        if (object[x] == value) { 
          object["ConfiguredSegments"] = replacevalue;
           break; 
        }
      }
    }
  }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda