file writing function working on localhost but not on azure - node.js

I have a function in my node js app that takes information and creates a csv file, then uploads it to the server. The code is below:
//check user has enough credits
if (req.user.credits >= 5) {
//check if user selected a recipient, and handle
let { name, address, state, country, city, postcode, message, note_name } = "";
let createRecipient = true;
if (req.body.recipient != "none") {
createRecipient = false
const recipient = await userController.getRecipientById(req.body.recipient);
name = recipient.name
address = recipient.address
state = recipient.state
country = recipient.country
city = recipient.city
postcode = recipient.postcode
message = req.body.message
note_name = req.body.note_name
} else {
name = req.body.name
address = req.body.address
state = req.body.state
country = req.body.country
city = req.body.city
postcode = req.body.postcode
message = req.body.message
note_name = req.body.note_name
}
const path = 'uploads\\notes_files\\';
const filename = path + randomUUID() + '.csv';
//first, save recipent to database
console.log(createRecipient + req.body.save_recipient)
if (createRecipient && req.body.save_recipient == 'on') {
db.query('INSERT into RECIPIENTS SET ?', {user_id: req.user.id, name: name, address: address, state: state, country: country, city: city, postcode: postcode }, function(err) {
if (err) throw err
});
}
//next, create a CSV file
const csvWriter = createCsvWriter({
path: filename,
header: [
{id: 'name', title: 'Name'},
{id: 'address', title: 'Address'},
{id: 'state', title: 'State'},
{id: 'country', title: 'Country'},
{id: 'city', title: 'City'},
{id: 'postcode', title: 'Postcode'},
{id: 'message', title: 'Message'}
]
});
const records = [
{name: name, address: address, state: state, country: country, city: city, postcode: postcode, message: message}
];
await csvWriter.writeRecords(records)
.then(() => {
let note_id;
db.query(`INSERT INTO notes SET ?`, {filename: 'temp', user_id: req.user.id, note_status: 'pending', note_name: note_name }, function(err, result) {
if (err) throw err;
// rename file to format 'note*id*_user*id*
note_id = result.insertId
const new_filename = 'note' + note_id + '_user' + req.user.id + '.csv'
//update in DB
db.query('UPDATE notes SET filename = ? WHERE note_id = ?', [ new_filename, note_id ], function(err) {
if (err) throw err;
//move to uploads folder
fs.rename(filename, path + new_filename, function(err) {
if (err) {
console.log(err);
res.send('There was a problem uploading your file. Please try again.');
}
//create notification before ending function
userController.createNotification(req.user.id, "New Note", "New note has been sent to our team for approval.");
res.redirect('/');
});
});
});
})
} else {
res.status(400).send('Not enough credits.')
}
}
this works fine on localhost, but when i deploy the app on an azure web app, i get this error in the azure logs:
2022-06-07T06:33:57.961918438Z node:internal/process/promises:246
2022-06-07T06:33:57.961969838Z triggerUncaughtException(err, true /* fromPromise */);
2022-06-07T06:33:57.961997638Z ^
2022-06-07T06:33:57.962012639Z
2022-06-07T06:33:57.962016639Z [Error: EINVAL: invalid argument, open 'uploads\notes_files\1d624787-2d06-41d7-909e-bb6283ea0efb.csv'] {
2022-06-07T06:33:57.962020839Z errno: -22,
2022-06-07T06:33:57.962024839Z code: 'EINVAL',
2022-06-07T06:33:57.962028639Z syscall: 'open',
2022-06-07T06:33:57.962102239Z path: 'uploads\\notes_files\\1d624787-2d06-41d7-909e-bb6283ea0efb.csv'
2022-06-07T06:33:57.962110639Z }
Any clue as to why this is working on localhost but not on azure?

Related

Casting error while saving in the database

I am using Angular as frontend and NodeJS for the backend.
I have a route that saves the data received from the frontend to the database. When I execute the save() method, I get prompted the following error:
err : ValidationError: conf.0: Cast to [Boolean] failed for value "[ {
name: 'v', percentage: 2, type: false, status: true } ]" (type string)
at path "conf.0"
Below is the route that stores the data:
app.post("/api/submitTaxCollection", (req, res) => {
console.log(req.body);
const submitTaxSchema = new addTaxesSchema(req.body);
try {
submitTaxSchema.save(function (err) {
if (err) return console.log("err : " + err);
});
} catch (error) {
console.log("ERROR : " + error);
return res.send(error);
}
});
and this is the schema.ts file:
var mongoose = require("mongoose");
//Define a schema
var taxSchema = mongoose.Schema;
var AddTaxSchema = new taxSchema({
parentId: String,
conf: [
{
name: String,
percentage: Number,
type: Boolean,
status: Boolean,
},
],
});
var newTaxesSchema = mongoose.model("addTaxSchema", AddTaxSchema);
module.exports = newTaxesSchema;
In Angular, model is setup as below:
export class TaxRatesConfigurationsModel {
name: string = "";
percentage: number = 0;
type: boolean = false;
status: boolean = true;
}
export class TaxRatesModel {
parentId: string = "";
conf: TaxRatesConfigurationsModel[] = [];
}
and I am calling the API as below:
this._httpService
.post(environment.url + "/api/submitTaxCollection", request)
.subscribe((data) => {
console.log(data);
});
when I console.log(req.body);, I get the following printed to the console (Nodejs):
{
parentId: '23948923nur8cw9yicnyu',
conf: [ { name: 'v', percentage: 2, type: false, status: true } ]
}
and the error occurs in Nodejs
What is causing this weird issue?

express-fileupload requires me to upload a file which is optional on the form

I have a challenge with express-fileupload when a user doesn't upload a file that is meant to be optional.
Someone should please help me out.
This is my code:
const file = req.files.document;
const file2 = req.files.document2;
const uploader = req.body.fullname;
const filename = `CV_${uploader}_${file.name}`;
const filename2 = `Cover_${uploader}_${file2.name}`;
let savedFile = filename.replace(/\s+/g, "");
let savedFile2 = filename2.replace(/\s+/g, "");
const path = "uploads/" + savedFile;
const path2 = "uploads/" + savedFile2;
file.mv(path, (err) => {
if (err) {
console.log(err);
}
});
file2.mv(path2, (err) => {
if (err) {
console.log(err);
}
});
The second file is optional for the user to upload. When the user doesn't upload it, it shows an error.
Please, how can I make it optional from here.
It shows an error like this:
Type Error: Cannot read property 'name' of undefined
Thank you so much.
So, I was able to find my way around the whole thing.
I did it like this...
app.post("/form", (req, res) => {
const file = req.files.document;
const file2 = req.files.document2;
const uploader = req.body.fullname;
const filename = `CV_${uploader}_${file.name}`;
let savedFile = filename.replace(/\s+/g, "");
const path = "uploads/" + savedFile;
file.mv(path, (err) => {
if (err) {
console.log(err);
}
});
// function to save file2 to server if it exists and send the filename to be used outside the function
const filename2 = file2 ? `Cover_${uploader}_${file2.name}` : null;
let savedFile2 = filename2 ? filename2.replace(/\s+/g, "") : null;
const path2 = filename2 ? "uploads/" + savedFile2 : null;
if (file2 && file2.name) {
const filename2 = `Cover_${uploader}_${file2.name}`;
let savedFile2 = filename2.replace(/\s+/g, "");
const path2 = "uploads/" + savedFile2;
file2.mv(path2, (err) => {
if (err) {
console.log(err);
}
});
}
// Saving to the database...
const date = new Date();
const dateNow = moment(date).format("llll");
const job = new Jobs({
position: req.body.positions,
language: req.body.lang,
fullName: req.body.fullname,
gender: req.body.gender,
education: req.body.education,
email: req.body.email,
address: req.body.address,
phone: req.body.phone,
fileCV: savedFile,
fileCover: savedFile2,
date: dateNow,
});
job.save((err) => {
if (!err) {
res.render("success");
}
});
// Sending to mail server
const output = `
<p> You have a new applicant! </p>
<h2> Contact Details </h2>
<ul>
<li>position: ${req.body.positions}</li>
<li>language: ${req.body.lang} </li>
<li>fullName: ${req.body.fullname}</li>
<li>gender: ${req.body.gender}</li>
<li>email: ${req.body.email}</li>
<li>address: ${req.body.address}</li>
<li>phone: ${req.body.phone}</li>
<li>education: ${req.body.education}</li>
</ul>
`;
const transporter = nodemailer.createTransport({
service: "localhost",
port: 1025,
secure: false, // true for 465, false for other ports
auth: {
user: "project.1", // generated ethereal user
pass: "secret.1", // generated ethereal password
},
tls: {
rejectUnauthorized: false,
},
});
let senderName = req.body.fullname;
let senderEmail = req.body.email;
//send mail with unicode symbols
let mailOptions = {
from: `"${senderName}" <${senderEmail}>`, // sender address
to: "mikejuwon737#gmail.com, sjobopisa#gmail.com", // list of receivers
subject: "Job Application ✔", // Subject line
text: "Check out my details here...", // plain text body
html: output, // html body
attachments: [
{ filename: `${savedFile}`, path: `${path}` },
{ filename: `${savedFile2}`, path: `${path2}` },
], // list of attachments
};
// sending mail with defined transport object
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err);
} else {
console.log("Message sent: %s", info.messageId);
// console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}
});
});

Function not returning anything in nodejs

I am creating a web app's backend , where different posts are stored and their categories are also stored. Since each category has its own properties (like description , color etc. ) , I've created a new category schema and storing the category reference in the article.
Here's my post route:
Code_1
Code_2
// CREATE ROUTE : adding New Article
app.post("/addnew", upload.single('image'), function(req,res){
//get data from form and add to news array
var title = req.body.title;
var image = req.body.image
if (req.file){
var imgURL = req.file.path;
}
var description = req.body.description;
var category = req.body.category;
var tag = req.body.tag;
// Handling the category entered by user
function checkCategory(name , color, totalArticles, desc){Category.find({name: category}, (err, foundCategory) => {
if(err){
console.log(err)
} else {
console.log("found category in starting of checkCategory function : " , foundCategory)
if (foundCategory[0]){
console.log("Category" + foundCategory + "already exists...")
return foundCategory
} else {
// var name = req.body.name
// var color = req.body.color
// var totalArticles = req.body.totalArticles
// var desc = req.body.desc
var category = {name: name , color : color , totalArticles: totalArticles || 0 , desc : desc }
Category.create(category, (err, newCategory) => {
if (err){
console.log(err)
} else {
console.log("New category Created : " , newCategory)
// category = newCategory
return newCategory
}
})
}
}
})
}
console.log("??????????????? category returned", category)
var nyaArticle= {title: title, imgURL: imgURL, description: description};
// create a new Article and save to db
Article.create(nyaArticle,function(err,newArticle){
if(err){
console.log(err);
} else {
// redirect back to main page
console.log("new article created")
console.log(newArticle)
category = checkCategory(req.body.name, req.body.color, req.body.totalArticles, req.body.desc)
console.log("checkCategory Returned :::::" , category)
newArticle.category.push(category)
newArticle.save()
res.redirect("/");
}
})
The function checkCategory checks if the category already exists or else it will create a new one .
But according to these logs , my function is not returning the category created , however the category is successfully created in DB and also can be seen in Logs
Articles App has started on port 3000
DB Connected...: cluster0-shard-00-00-ktzf1.mongodb.net
??????????????? category returned undefined
new article created
{
category: [],
hits: 0,
tag: [],
comments: [],
_id: 60be0fe92a8b88a8fcea71dc,
title: 'TESTING',
description: 'TESTING',
created: 2021-06-07T12:24:09.563Z,
__v: 0
}
checkCategory Returned ::::: undefined
found category in starting of checkCategory function : []
New category Created : {
totalArticles: 444,
_id: 60be0fea2a8b88a8fcea71dd,
name: 'TESTING',
color: 'RED ALERT',
desc: 'THiS TESTING',
__v: 0
}
due to this null is getting stored in my category in
DB
Am I using the right approach or should I follow some other approach, any help is much welcomed.
The categorySchema looks like this :
var categorySchema = new mongoose.Schema({ name: String, color: String, totalArticles: { type:Number, default: 0 }, desc : String });
ArticleSchema:
var newSchema = new mongoose.Schema({
title: String,
imgURL: String, //{type: String, default: "https://source.unsplash.com/1600x1080/?news"},
description: String,
// category: String,
category: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
}
],
hits : {
type: Number ,
default : 0
},
tag: [
{type: String}
],
created: {type: Date, default: Date.now},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
You are assigning var category inside the callback function returned from your checkCategory, and that var is only available inside that callback.
Besides, you code have several other problems, like Category.find({name: category}) which will never return anything. (it should be {name:name}).
In general, you'll be much better off using async\await, (coupled with a try\catch, if you like):
async function checkCategory(name, color, totalArticles, desc) {
try {
let category = await Category.findOne({ name });
if (category) {
console.log(`Category ${category.name} already exists...`);
return category;
}
else {
let newCategory = await Category.create({ name: name, color: color, totalArticles: totalArticles || 0, desc: desc });
console.log("New category Created : ", newCategory);
return newCategory;
}
} catch (error) {
console.log(err)
}
}
And in your router function:
app.post("/addnew", upload.single('image'), async function(req,res){
let {name, color, totalArticles, desc} = req.body;
let category = await checkCategory(name, color, totalArticles, desc);
let newArticle = await Article.create({ title: title, imgURL: imgURL, description: description, category: [category] });
res.redirect("/");
}

I'm trying to submit a form with Expess.js but I'm having an error

exports.campagne_add_post = function(req, res, next) {
// Validate fields.
req.assert('name', 'Please fill the name').isLength({ min: 1 }).trim().withMessage('First name must be specified.')
.isAlphanumeric().withMessage('First name has non-alphanumeric characters.');
req.assert('date_debut', 'Invalid date_debut').isISO8601();
req.assert('date_fin', 'Invalid date_fin').isISO8601();
req.assert('agence', 'Please fill agence name').isLength({ min: 1 }).trim().withMessage('Agence must be specified.')
.isAlphanumeric().withMessage('Agence has non-alphanumeric characters.');
req.assert('annonceur', 'Please fill the annonceur name').isLength({ min: 1 }).trim().withMessage('Annonceur name must be specified.')
.isAlphanumeric().withMessage('Annonceur name has non-alphanumeric characters.');
req.assert('groupe_annonceur', 'Please fill groupe annonceur').isLength({ min: 1 }).trim().withMessage('Groupe annonceur must be specified.')
.isAlphanumeric().withMessage('Groupe annonceur has non-alphanumeric characters.');
req.assert('produit', 'Please fill product name').isLength({ min: 1 }).trim().withMessage('Poduct name must be specified.')
.isAlphanumeric().withMessage('Product name has non-alphanumeric characters.');
var errors = req.validationErrors();
console.log(errors);
if (!errors) {
// Sanitize fields (using wildcard).
sanitizeBody('*').trim().escape();
var campagne = new Campagne(
{
name: req.body.name,
date_debut: req.body.date_debut,
date_fin: req.body.date_fin,
agence: req.body.agence,
annonceur: req.body.annonceur,
groupe_annonceur: req.body.groupe_annonceur,
produit: req.body.produit
}
);
Campagne.findOne({ 'name': req.body.name })
.exec(function (err, found_name) {
if (err) {
var errors_detail = ("Error Insert : %s ", err);
req.flash('msg_error', errors_detail);
res.render('campagne/add-campagne',
{
name: req.body.name,
date_debut: req.body.date_debut,
date_fin: req.body.date_fin,
agence: req.body.agence,
annonceur: req.body.annonceur,
groupe_annonceur: req.body.groupe_annonceur,
produit: req.body.produit,
});
}
if (found_name) {
req.flash('msg_error', 'Campagne with the same name already existe');
res.render('campagne/add-campagne',
{
name: req.body.name,
date_debut: req.body.date_debut,
date_fin: req.body.date_fin,
agence: req.body.agence,
annonceur: req.body.annonceur,
groupe_annonceur: req.body.groupe_annonceur,
produit: req.body.produit,
});
}
else {
if(req.body.date_debut > req.body.date_fin){
req.flash('msg_error', 'date_debut must be before date_fin');
res.render('campagne/add-campagne',
{
name: req.body.name,
date_debut: req.body.date_debut,
date_fin: req.body.date_fin,
agence: req.body.agence,
annonceur: req.body.annonceur,
groupe_annonceur: req.body.groupe_annonceur,
produit: req.body.produit
});
}else {
console.log(req.body.name +'\n');
console.log(req.body.date_debut +'\n');
console.log(req.body.date_fin +'\n');
console.log(req.body.agence +'\n');
console.log(req.body.annonceur +'\n');
console.log(req.body.produit);
campagne.save(function (err) {
if (err) {
var errors_detail = ("Error Insert : %s ", err);
req.flash('msg_error', errors_detail);
res.render('campagne/add-campage',
{
name: req.body.name,
date_debut: req.body.date_debut,
date_fin: req.body.date_fin,
agence: req.body.agence,
annonceur: req.body.annonceur,
groupe_annonceur: req.body.groupe_annonceur,
produit: req.body.produit
});
}
// Genre saved. Redirect to genre detail page.
req.flash('msg_info', 'Create campagne success');
res.redirect('/campagnes');
});
}
}
});
} else {
console.log(errors);
errors_detail = "Sory there are error" + " <ul>" ;
for (i in errors)
{
error = errors[i];
errors_detail += ' <li>'+error.msg+'</li>';
}
errors_detail += "</ul>";
req.flash('msg_error', errors_detail);
res.render('campagne/add-campagne',
{
name: req.body.name,
date_debut: req.body.date_debut,
date_fin: req.body.date_fin,
agence: req.body.agence,
annonceur: req.body.annonceur,
groupe_annonceur: req.body.groupe_annonceur,
produit: req.body.produit,
});
}
};
When I submit my form I have this message :
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
I saw one of the causes of the error is the redirect in my controller.
I also have a $__save.error in mongoose.
If I can get somme help it will be nice.
Because you aren't returning whenever you are calling res.render. This way you are trying to send response multiple times, hence, setting headers after sending first response.
e.g.
Campagne.findOne({ 'name': req.body.name })
.exec(function (err, found_name) {
if (err) {
var errors_detail = ("Error Insert : %s ", err);
req.flash('msg_error', errors_detail);
// you should return here, because it can go to following condition
return res.render('campagne/add-campagne',{
// some code
});
}
if (found_name) {
req.flash('msg_error', 'Campagne with the same name already existe');
return res.render('campagne/add-campagne', {
// some code
});
}
Do it for all conditions.

How to do Fhir?

I'm trying to learn the basics of fhir and want to implement in node js.
I have come across the following code https://github.com/FHIR/fhir.js
In that it says that i have to create a instance of FHIR client?
I know my question is dumb, so can i get any clarifications on the topic.
I have started learning node a few days back.
Thanks in advance!
var config = {
// FHIR server base url
baseUrl: 'http://myfhirserver.com',
auth: {
bearer: 'token',
// OR for basic auth
user: 'user',
pass: 'secret'
},
// Valid Options are 'same-origin', 'include'
credentials: 'same-origin',
headers: {
'X-Custom-Header': 'Custom Value',
'X-Another-Custom': 'Another Value',
}
}
myClient = fhir(config, adapter)
Above is the code for creating an instance of Fhir client, I want to know where should i implement this code and access a fhir server.
From the README, for use with Node:
var mkFhir = require('fhir.js');
var client = mkFhir({
baseUrl: 'http://try-fhirplace.hospital-systems.com'
});
client
.search( {type: 'Patient', query: { 'birthdate': '1974' }})
.then(function(res){
var bundle = res.data;
var count = (bundle.entry && bundle.entry.length) || 0;
console.log("# Patients born in 1974: ", count);
})
.catch(function(res){
// Error responses
if (res.status){
console.log('Error', res.status);
}
// Errors
if (res.message){
console.log('Error', res.message);
}
});
I would recommend using one of the publicly available FHIR test servers as outlined here: http://wiki.hl7.org/index.php?title=Publicly_Available_FHIR_Servers_for_testing
It seems as though you are generating a client for communicating with the FHIR server but you would need to update the base URL in the third line of your code.
FHIR WITH NODEJS
First we need to fetch the access Token
After fetching the token we can easily create the Patient record just by passing the values via POSTMAN as req.body and than it will manipulate the request data into FHIR.
We can fetch the Patient record as per our response body.
All three services are coded below:
const CLIENT_ID = FHIR_CLIENT_ID;
const APP_SECRET = FHIR_CLIENT_SECRET;
const { BASE, RESOURCE } = fhir;
const instance = axios.create({
baseURL: RESOURCE,
});
const getAccessToken = async () => {
const response = await axios({
url: `${BASE}/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/oauth2/token`,
method: 'post',
data: `grant_type=Client_Credentials&resource=${RESOURCE}`,
auth: {
username: CLIENT_ID,
password: APP_SECRET,
},
});
return response.data.access_token;
};
const createPatient = async (patientBody) => {
const {
firstName,
middleIniital,
lastName,
birthDate,
gender,
reference,
address,
city,
state,
zipcode,
email,
phone,
ssn,
mrn,
} = patientBody;
const newFhirPatient = {
resourceType: 'Patient',
name: [
{ text: 'First Name', given: [firstName] },
{ text: 'Middle Name', given: [middleIniital] },
{ text: 'Last Name', given: [lastName] },
],
birthDate,
gender,
managingOrganization: { type: 'Organization', reference },
address: [{ text: address, city, state, postalCode: zipcode }],
contact: [
{
telecom: [
{ system: 'email', value: email },
{ system: 'phone', value: phone },
],
relationship: {
coding: [
{ display: 'SSN', code: ssn },
{ display: 'MRN', code: mrn },
],
},
},
],
};
const accessToken = await getAccessToken();
try {
const response = await instance.post('/Patient', newFhirPatient, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
throw error;
}
};
const getPatient = async () => {
const accessToken = await getAccessToken();
try {
const response = await instance.get('/Patient', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const data = [];
for (let i = 0; i < response.data.entry.length; i++) {
const entry = response.data.entry[i];
var id = (entry.resource.id !== undefined) ? entry.resource.id : "";
var firstName = (entry.resource.name?.[0]?.given?.[0] !== undefined) ? entry.resource.name?.[0]?.given?.[0] : "";
var middleName = (entry.resource.name?.[1]?.given?.[0] !== undefined) ? entry.resource.name?.[1]?.given?.[0] : "";
var lastName = (entry.resource.name?.[2]?.given?.[0] !== undefined) ? entry.resource.name?.[2]?.given?.[0] : "";
var birthDate = (entry.resource.birthDate !== undefined) ? entry.resource.birthDate : "";
var gender = (entry.resource.gender !== undefined) ? entry.resource.gender : "";
var address = (entry.resource.address?.[0]?.text !== undefined) ? entry.resource.address?.[0]?.text : "";
var city = (entry.resource.address?.[0]?.city !== undefined) ? entry.resource.address?.[0]?.city : "";
var state = (entry.resource.address?.[0]?.state !== undefined) ? entry.resource.address?.[0]?.state : "";
var zipcode = (entry.resource.address?.[0]?.zipcode !== undefined) ? entry.resource.address?.[0]?.zipcode : "";
var ssn = (entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[0].code !== undefined) ? entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[0].code : "";
var mrn = (entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[1].code !== undefined) ? entry.resource.contact?.[0]?.relationship?.[0]?.coding?.[1].code : "";
var email = (entry.resource.contact?.[0]?.telecom?.[0]?.value !== undefined) ? entry.resource.contact?.[0]?.telecom?.[0]?.value : "";
var phone = (entry.resource.contact?.[0]?.telecom?.[1]?.value !== undefined) ? entry.resource.contact?.[0]?.telecom?.[1]?.value : "";
var organizationId = (entry.resource.managingOrganization?.reference !== undefined) ? entry.resource.managingOrganization?.reference : "";
data.push({
id,
firstName,
middleName,
lastName,
birthDate,
gender,
address,
city,
state,
zipcode,
email,
phone,
ssn,
mrn,
organizationId,
});
}
return data;
} catch (error) {
throw error;
}
};
After getting the access Token you can create the Patient like this in NodeJS
and send the data into FHIR in their manner
const createPatient = async (patientBody) => {
const {
firstName,
middleIniital,
lastName,
birthDate,
gender,
reference,
address,
city,
state,
zipcode,
email,
phone,
ssn,
mrn,
} = patientBody;
const newFhirPatient = {
resourceType: 'Patient',
name: [
{ text: 'First Name', given: [firstName] },
{ text: 'Middle Name', given: [middleIniital] },
{ text: 'Last Name', given: [lastName] },
],
birthDate,
gender,
managingOrganization: { type: 'Organization', reference },
address: [{ text: address, city, state, postalCode: zipcode }],
contact: [
{
telecom: [
{ system: 'email', value: email },
{ system: 'phone', value: phone },
],
relationship: {
coding: [
{ display: 'SSN', code: ssn },
{ display: 'MRN', code: mrn },
],
},
},
],
};
const accessToken = await getAccessToken();
try {
const response = await instance.post('/Patient', newFhirPatient, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
throw error;
}
};

Resources